SQL Update Row,包含来自类似Row的数据的信息

时间:2016-11-30 17:15:08

标签: sql sql-server

上周我们进行了系统更新,并且我们客户的一系列要求截止日期已更改。我试图弄清楚如何将它们恢复到原始状态。幸运的是,有一行数据具有我需要的确切信息,我只是无法弄清楚如何编写UPDATE语句并结合正确的LIKE *修饰符。

这就是我正在处理的问题:

 PartNo   |   Datedue   
------------------------
 G42786   |   12/31/16    --this row
 S42786   |   10/07/25   
 M42786   |   10/07/25  
 G54231   |   11/20/16    --this row
 M54321   |   01/15/22   
 S54321   |   01/15/22  

评论的行具有正确的日期。我希望以该日期更新以M和S开头的部件,只要唯一部件ID(42786和54321)与G部件相同即可。有没有办法做到这一点?

感谢。

更新

所以我备份了我试图修改的表并试图运行它:

WITH Splitted AS
(
  SELECT LEFT(PartNo,1) AS FirstLetter
      ,CAST(SUBSTRING(PartNo,2,1000) AS INT) AS PartNumber
      ,DueDate
FROM Orderdet AS d
)
,Joined AS
(
SELECT *
FROM Splitted
     CROSS APPLY(SELECT x.DueDate FROM Splitted AS x WHERE x.FirstLetter='G'       AND x.PartNumber=Splitted.PartNumber) AS A(NewDatedue)
WHERE FirstLetter<>'G'
   )

UPDATE Joined SET Duedate=NewDatedue;

我收到了这个错误:

Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value '37351-0' to data type int.

更新

在语句中将INT更改为Varchar并且已成功执行。更改了我尝试更新的记录...但不幸的是错误的日期。我将不得不做更多的探索,并找出它从哪里拉出日期

1 个答案:

答案 0 :(得分:1)

您可以使用可更新的CTE

模拟 -table

DECLARE @dummy TABLE(PartNo VARCHAR(100),Datedue DATE);
INSERT INTO @dummy VALUES
 ('G42786','2016-12-31')
,('S42786','2025-10-07')
,('M42786','2025-10-07')
,('G54321','2016-11-20')
,('M54321','2022-01-15')
,('S54321','2022-01-15');

- 第一个CTE将分别获得第一个字母和PartNo

WITH Splitted AS
(
    SELECT LEFT(PartNo,1) AS FirstLetter
          ,CAST(SUBSTRING(PartNo,2,1000) AS INT) AS PartNumber
          ,Datedue
    FROM @dummy AS d
)

- 第二个CTE使用CROSS APPLY来获取相应的值

,Joined AS
(
    SELECT *
    FROM Splitted
        CROSS APPLY(SELECT x.Datedue FROM Splitted AS x WHERE x.FirstLetter='G' AND x.PartNumber=Splitted.PartNumber) AS A(NewDatedue)
    WHERE FirstLetter<>'G'
)

- 这可以直接更新

UPDATE Joined SET Datedue=NewDatedue;

- 检查结果

SELECT * FROM @dummy;