SQL Update查询和Where子句

时间:2014-11-08 14:52:05

标签: sql sql-server tsql

如果我有以下表格:

  • Materials(MaterialID,姓名)
  • Teacups(TeacupID,Description,FriendlyName,MaterialID)

使用以下数据:

材料

(1, 'Glass')
(2, 'Porcelain')
(3, 'Iron')

茶杯

(1, 'Desc1', 'Name1', 1)
(2, 'Desc2', 'Name2', 1)
(3, 'Desc3', 'Name3', 1)
(4, NULL, 'Name1', 2)
(5, NULL, 'Name2', 2)
(6, 'Desc6', 'Name3', 2)
(7, 'Desc7', 'Name1', 3)
(8, NULL, 'Name2', 3)
(9, NULL, 'Name3', 3)

如何更新所有描述(无论是否为NULL)与具有MaterialID=1的Teacup具有相同的描述,并与FriendlyName匹配

所以数据需要看起来像:

茶杯

(1, 'Desc1', 'Name1', 1)
(2, 'Desc2', 'Name2', 1)
(3, 'Desc3', 'Name3', 1)
(4, 'Desc1', 'Name1', 2)
(5, 'Desc2', 'Name2', 2)
(6, 'Desc3', 'Name3', 2)
(7, 'Desc1', 'Name1', 3)
(8, 'Desc2', 'Name2', 3)
(9, 'Desc3', 'Name3', 3)

4 个答案:

答案 0 :(得分:2)

最简单的方法是在JOIN clause语句中使用UPDATE。试试这个..

UPDATE A
SET    A.Description = B.Description
FROM   Teacups A
       JOIN (SELECT Description,
                    FriendlyName
             FROM   teacups
             WHERE  MaterialID = 1) b
         ON a.FriendlyName = B.FriendlyName 
Where A.MaterialID != 1 

答案 1 :(得分:1)

UPDATE tUp
   SET tUp.Description = t1.Description
  FROM Teacups tUp
  JOIN Teacups t1       
    ON t1.FriendlyName = tUp.FriendlyName 
   and tUp.MaterialID <> 1 
   and t1.MaterialID   = 1
 --and tUp.Description <> t1.Description

答案 2 :(得分:0)

您可能需要使用MERGE语句,如下所示:

 MERGE INTO Teacups as trg
 USING (
         SELECT FriendlyName, Description FROM Teacups WHERE MaterialID = 1
       ) AS src
 ON trg.FriendlyName = src.FriendlyName
 WHEN MATCHED THEN
    UPDATE SET trg.Description = src.Description;

答案 3 :(得分:-1)

可以创建临时表并插入此查询的值:

SELECT * from teacups WHERE MaterialID = 1; --insert into table 'temp'

然后你可以更新你的表格:

UPDATE teacups SET description = temp.description WHERE teacups.FriendlyName = temp.FriendlyName;