假設(shè)新建一個表: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)這個情況下,每插入一筆數(shù)據(jù)的時候,id字段都是以1為頻率自增長.如果我想設(shè)置id為如果是男生,則id為基數(shù), 如果為女生,則id為偶數(shù).就是判斷bit 為0 是女生, bit 為 非0 則為男生當(dāng)為男生時候,則identity(1131301101,2)當(dāng)為女生時候,則identity(1131301102,2)不知道這樣的情況,該怎么來建表?學(xué)生表只是個舉例,別在意它的實際應(yīng)用.只是提供這樣一個想法, 不知道各位有什么方法來實現(xiàn)不?
2 回答

米脂
TA貢獻1836條經(jīng)驗 獲得超3個贊
寫個函數(shù)dbo.f_getid(sex)
函數(shù)功能判斷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
提交
取消