SQL Server : row_number over primary key

女生的网名这么多〃 提交于 2020-06-01 08:58:27

问题


Is there any way to create column that will be increased and reset over primary key?

Example:

Table A ([Code], [Type], [Line No_])

Primary key is ([Code], [Type])

And when I add a new row, I want to auto generate [Line No_] like this:

Code   Type   Line No_
-----------------------
'U1'     0     1000
'U1'     0     2000
'U1'     1     1000

Something like ROW_NUMBER but auto generated on insert row


回答1:


No, you can't use a window function in a computed column. Computed columns must be scalar values. However, this is a perfect use case for a view.

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


来源:https://stackoverflow.com/questions/52841714/sql-server-row-number-over-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!