一般:
SELECT *,ROW_NUMBER() over(ORDER BY ([列名称])) as RowNum from [production qty]
是按照某个列排序,并生成行号。
在一个数据表中,要保持原来的表顺序。
SELECT *,ROW_NUMBER() over(ORDER BY (SELECT 1)) as RowNum from [production qty]
来源From:http://stackoverflow.com/questions/4810627/sql-server-2005-row-number-without-over
INSERT TargetTable (ID, FIELD)
SELECT
Row_Number() OVER (ORDER BY (SELECT 1))
+ Coalesce((SELECT Max(ID) FROM TargetTable WITH (TABLOCKX, HOLDLOCK)), 0),
FieldValue
FROM SourceTable
WHERE [somecondition] 解释说明:
|
I think, the way @IDOffset is initialised is incorrect (the mistake actually comes from the original post, so it has simply been replicated in the answer). If TargetTable is empty, MAX(ISNULL(ID,0)) will result in NULL (regardless of using ISNULL()) so @IDOffset becomes NULL too. The statement should probably be rewritten like this: SET @IDOffset = ISNULL((SELECT MAX(ID) FROM TargetTable), 0). On the other point, I like the unpretentiousness of ORDER BY (SELECT 1). –
Andriy M
Jan 27 '11 at 8:48
| |
|
Turns out my replacement for SELECT @IDOffset... could be better. At least it is possible to make it much simpler – like this: SELECT ISNULL(MAX(ID),0) FROM TargetTable. –
Andriy M
Jan 27 '11 at 12:25
|
本文介绍如何使用SQL的ROW_NUMBER()函数为数据表中的记录生成行号,并保持原有的表顺序。此外,还详细解释了如何通过INSERT语句结合ROW_NUMBER()函数实现新记录的插入,包括初始化ID偏移量的正确方式。

被折叠的 条评论
为什么被折叠?



