Sql server生成序列号

wmomyfyw  于 2022-11-21  发布在  SQL Server
关注(0)|答案(1)|浏览(252)

SQL Server查询。我记得我发现了一种生成序列号的方法,在选择数据时不使用ROW_NUMBER函数。但我现在不记得了
它是这样的:

DECLARE @num int
SET @num = 0
SELECT ??? as [Index], Name FROM Product

The result will be:
Index    | Name
1        | Rug
2        | Water
3        | Oil

我记得???像@num = @num + 1,在这里它使用了函数CAST或ISNULL或CONVERT或其他函数(我不记得了,但我确信它没有使用ROW_NUMBER()函数)
有没有办法做到这一点?
使用Row_number()时的问题:

select Id, Case when [type] = 'abc' then 1 else 0 end as Classification,
       ???? as DisplayOrder
from Product
order by Classification, ..., ..., ...

如何在这里使用Row_number()?我尝试使用Row_number(over order by(select 1)),但是它“order by Classification,...”语句在生成Row_number之后运行。这意味着序列号在order by语句动作之前生成。

fwzugrvs

fwzugrvs1#

尝试
使用Row_Number()

SELECT ROW_NUMBER() OVER(ORDER BY NEWID()) as [Index], Name FROM Product

编辑2:
使用Identity columnTemporary Table

create table #x([Index] bigint identity(1,1),Name varchar(200))

insert into #x(Name)
SELECT Name FROM Product

select * from #x

drop table #x

相关问题