SQL Server Table Value Constructor with identity column

dgtucam1  于 2023-05-28  发布在  其他
关注(0)|答案(1)|浏览(164)

In SQL Server how can I add a ordinal/identity/row number to this result set?

  1. select *
  2. from (VALUES('c'), ('a'), ('b')) t(value)
value
c
a
b

So it returns the same as this:

  1. select *
  2. from STRING_SPLIT('c,a,b', ',', 1) t
valueordinal
c1
a2
b3

I don't want to just do VALUES(1,'c'),(2,'a'),(3,'b') because there will be a long list that will change from time to time and can't have gaps in the ordinal.

g6ll5ycj

g6ll5ycj1#

You can't do it using the values constructor, the closest you can get is to use a table variable with an identity column e.g.

  1. declare @Test table ([Value] varchar(32), Ordinal int identity (1,1));
  2. insert into @Test ([Value])
  3. values ('c'),('a'),('b');
  4. select *
  5. from @Test
  6. order by Ordinal;

Returns

ValueOrdinal
c1
a2
b3
展开查看全部

相关问题