Sql server生成序列号

时间:2015-09-30 10:42:01

标签: sql sql-server

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(按顺序(选择1)),但是“按分类排序,...”语句在生成Row_number之后运行。这意味着序列号是在order by statement动作之前生成的。

1 个答案:

答案 0 :(得分:1)

尝试

使用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
相关问题