为了账号安全,请及时绑定邮箱和手机立即绑定

以下是sql关于id自增长identity的相关问题,麻烦求助大佬解释!

以下是sql关于id自增长identity的相关问题,麻烦求助大佬解释!

海绵宝宝撒 2021-07-21 19:15:57
假设新建一个表: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



查看完整回答
反对 回复 2021-07-25
  • 2 回答
  • 0 关注
  • 348 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信