SQL语句:使用RowNumber函数但保持原来表的顺序。

一般:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值