问题
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