SQL Update行,其中First Row为NULL

时间:2013-12-02 19:15:52

标签: sql sql-server-2008-r2 cursor

我正在使用SQL Server 2008 R2并且需要从另一个日期值为null的表更新每个SOrder的第一行。在下面的示例中,我将评估SOrder = 000791REVDE2是否为空,如果是,我会

SELECT SOrder, MyDates.NewDate FROM MyDates

UPDATE MyTable SET DateVate = MyDates.NewDate WHERE REVDE2 IS NULL

REVDE3必须保持为空,直到MyDates.NewDate> REVDE2 DateValue

SOrder      Line    FieldName       DateValue
000791      0001    REVDEL          01/12/2013
000791      0001    REVDE2          NULL
000791      0001    REVDE3          NULL
000992      0001    REVDEL          05/01/2014
000992      0001    REVDE2          08/12/2014
000992      0001    REVDE3          NULL

我不确定光标是否可行,我唯一关心的是运行游标的速度。

2 个答案:

答案 0 :(得分:0)

以下是完整工作代码示例:http://sqlfiddle.com/#!3/fd3d1/15

这是将执行更新的实际SQL代码。上面的SQL Fiddle包含Schema,Inserts和Updates。

此代码中的假设是FieldValue不会超出REVDE9,因为如果它达到REVDE10,则查询中的排序将会重击!

;WITH CTE AS
(
   SELECT *,
         ROW_NUMBER() OVER (PARTITION BY SOrder ORDER BY FieldName ASC) AS rn
   FROM MyTable 
   WHERE DateValue IS NULL 
)
-- -- SELECT * FROM CTE
UPDATE MyTable
SET DateValue = md.NewDate
FROM MyTable mt 
    INNER JOIN MyDates md ON mt.SOrder = md.SOrder
    INNER JOIN cte c ON mt.SOrder = c.SOrder
        AND mt.FieldName = c.FieldName
        AND c.rn = 1;

答案 1 :(得分:0)

WITH t AS (
  SELECT *,ROW_NUMBER() OVER(PARTITION BY SOrder ORDER BY FieldName) AS rownum
  FROM MyDates
  WHERE DateValue IS NULL
)
UPDATE t
SET DateValue = NewDate
WHERE rownum = 1