SQL - 如何在自动生成的临时表中添加自动增量 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13486353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:14:19  来源:igfitidea点击:

SQL -How to add an auto incremental id in a auto generated temporary table

sqlsql-server

提问by riad

I have a query like below and it generate a temporary table automatically based on parameter. So, the number of column of this table can be vary. Now , i need to add an auto incremental id column into this table.How i do it?

我有一个如下所示的查询,它根据参数自动生成一个临时表。因此,该表的列数可能会有所不同。现在,我需要在这个表中添加一个自动增量 id 列。我是怎么做的?

SELECT @SourceFields INTO ##StoreSourceInfo FROM testdb.dbo.@SourceTable

Note: 1) Number of source field & name of table pass using the parameter @SourceFields & @SourceTable. 2) So, the number of column can be vary on ##StoreSourceInfo table.

注意:1) 源字段数和表名使用参数传递@SourceFields & @SourceTable。2) 因此,##StoreSourceInfo 表上的列数可能会有所不同。

Current Result:

当前结果:

select * from ##StoreSourceInfoshows only the available column.

select * from ##StoreSourceInfo仅显示可用列。

Expected Result:select * from ##StoreSourceInfoquery will show an additional auto incremental id column& all rest of the column available in the temp table.

预期结果:select * from ##StoreSourceInfo查询将显示额外的自动增量 id 列和临时表中可用的所有其余列。

Hope you get me. Thanks in advance.

希望你能得到我。提前致谢。

采纳答案by Stuart Ainsworth

Use the identity function. See the link for an example. http://msdn.microsoft.com/en-us/library/ms189838.aspx

使用身份函数。有关示例,请参见链接。 http://msdn.microsoft.com/en-us/library/ms189838.aspx

回答by user2667356

SELECT
  IDENTITY(INT, 1, 1) AS id
INTO #Temptable
FROM User

回答by Rajender Sehgal

You can use row_number function

您可以使用 row_number 函数

Select ROW_NUMBER() over (order by T.field1) rownum
, T.field1, T.field2 into #temp1 
from @Table T

回答by Vimal bhatt

You have to try with following query to get your excepted result to add a extra auto increment column :

您必须尝试使用​​以下查询来获取异常结果以添加额外的自动增量列:

SELECT 
    IDENTITY(INT, 1,1) AS Rank, 
    @SourceFields 
INTO 
    ##StoreSourceInfo 
FROM 
    testdb.dbo.@SourceTable

Means apply IDENTITYfunction...

意思是应用IDENTITY函数...