主键上的MSSQL行号

时间:2018-10-16 18:19:53

标签: sql-server insert row-number

嗨,

是否有任何方法可以创建column并通过Primary key进行重置?

示例table A ([Code],[Type],[Line No_])

主键([Code],[Type])

当我添加一行([Code],[Type])时,我想像这样自动生成[Line No_]

[Code],[Type],[Line No_]
'U1', 0, 1000
'U1', 0, 2000
'U1', 1, 1000

类似ROW_NUMBER,但会在插入行上自动生成

1 个答案:

答案 0 :(得分:0)

否,您不能在计算列中使用窗口函数。计算列必须是标量值。但是,这是视图的理想用例。

See the DB Fiddle For the Code Below

create table myTable ([Code] varchar(20),[Type] int)
go

insert into myTable
values
('U1',0)
,('U1',0)
,('U1',1)
go

create view MyView 
as
select *
    ,Line_No = row_number() over (partition by [Code], [Type] order by (select null)) * 1000
from myTable
go

select * from myView