在默认值内获取@@ identity或Scope_identity()映射到标量函数

时间:2019-04-28 12:40:42

标签: sql-server

我有一个表,其中ID作为标识列,Code作为varchar列。 Code的默认值设置为标量函数X

在该标量函数X中,获取scope_identity()@@identity返回null。有没有不使用插入触发器就获得插入身份的方法?

非常感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您可以完全跳过ID和IDENTITY并生成code作为主键。 EG

--drop table if exists t
--drop sequence t_seq
--drop function t_key_gen 
go
create sequence t_seq start with 1000 increment by 1

go
create or alter function t_key_gen(@i int)
returns char(10)
as
begin
   return concat('AB',right(concat('0000000000',@i),8));
end

go

create table t(code char(10) primary key default dbo.t_key_gen(next value for t_seq), a int)

go

insert into t(a) values (1),(2),(3)

select * from t