一般:
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
|