假設新建一個表:create table student (s_id int identity(1131301101,1) primary key,s_name varchar(12) not null,s_sex bit,s_age int check(s_age >0 and s_age <100)s_addr varchar(100) default '' not null)這個情況下,每插入一筆數據的時候,id字段都是以1為頻率自增長.如果我想設置id為如果是男生,則id為基數, 如果為女生,則id為偶數.就是判斷bit 為0 是女生, bit 為 非0 則為男生當為男生時候,則identity(1131301101,2)當為女生時候,則identity(1131301102,2)不知道這樣的情況,該怎么來建表?學生表只是個舉例,別在意它的實際應用.只是提供這樣一個想法, 不知道各位有什么方法來實現不?
2 回答

米脂
TA貢獻1836條經驗 獲得超3個贊
寫個函數dbo.f_getid(sex)
函數功能判斷sex并取最大
create table test(id int not null,sex bit)
go
create function dbo.f_getid(@sex bit)
returns int
as
begin
declare @ids int
select @ids = max(id) from test
if @sex = 0 --women
set @ids = isnull(@ids,0) + (case isnull(@ids,2)%2 when 0 then 2 else 1 end)
if @sex = 1 --man
set @ids = isnull(@ids,0) + (case isnull(@ids,2)%2 when 0 then 1 else 2 end)
return @ids
end
go
insert into test values(dbo.f_getid(1),1)
go
insert into test values(dbo.f_getid(0),0)
go
添加回答
舉報
0/150
提交
取消