如何将select语句转换为update语句

时间:2014-09-03 21:06:13

标签: sql-server-2008

我正在尝试创建一个与此Select语句相同或更多功能的Update语句:

SELECT * 
FROM table 
WHERE field1 = 1 
AND field2 NOT IN (SELECT field2 
                   FROM table 
                   WHERE field1 = 0) 

2 个答案:

答案 0 :(得分:0)

UPDATE [Table1]
 SET [Column1] = ?
    ,[Column2] = ?
  --,...  other columns and so on....
WHERE field1 = 1 
  AND NOT EXISTS (SELECT 1
                  FROM Table2 
                  WHERE field1 = 0
                   AND  Field2 = [Table1].Field2 )

答案 1 :(得分:0)

在这种情况下,从selectupdate的转换非常简单,因为它不需要SQL Server的非标准专有更新语法。

UPDATE table 
SET    field3 = 'X' 
WHERE  field1 = 1 
       AND field2 NOT IN (SELECT field2 
                          FROM   table 
                          WHERE  field1 = 0) 

翻译它的另一种方法是将整个select语句放在cte中并更新它。

WITH t 
     AS (SELECT * 
         FROM   table 
         WHERE  field1 = 1 
                AND field2 NOT IN (SELECT field2 
                                   FROM   table 
                                   WHERE  field1 = 0)) 
UPDATE t 
SET    field3 = 'Y' 

如果涉及的任何列可以为空,not exists可能会有更好的计划。