如何将此INSERT INTO语句转换为UPDATE SET语句

时间:2012-04-04 14:10:59

标签: sql sql-server-2008 where

我尝试将以下INSERT INTO转换为UPDATE SET但我遇到了一些麻烦......我正在使用SQL Server 2008

INSERT INTO tableA
(c_id, status)
SELECT  tableB.c_id, COUNT(*)
FROM    tableB
    LEFT JOIN tableC
        ON tableB.c_id = tableC.c_id
  WHERE tableC.c_id != tableC.c_id_update
GROUP BY tableB.bl_id

到目前为止我想出了什么...但是我在变量c_id的分配和关键字'SET'之后的项目时遇到了麻烦。

UPDATE tableA SET
c_id = tableB.c_id
,items -- count(*)??
SELECT  tableB.c_id, COUNT(*)
FROM    tableB
    LEFT JOIN tableC
        ON tableB.c_id = tableC.c_id
  WHERE tableC.c_id != tableC.c_id_update
GROUP BY tableB.bl_id

2 个答案:

答案 0 :(得分:1)

UPDATE A
SET
    A.status = X.c
FROM 
tableA A INNER JOIN (
SELECT  tableB.c_id, COUNT(*) as c
FROM    tableB
    LEFT JOIN tableC
        ON tableB.c_id = tableC.c_id
  WHERE tableC.c_id != tableC.c_id_update
GROUP BY tableB.bl_id ) X
ON A.c_id = X.c_id

答案 1 :(得分:0)

我分享了将任何选择转换为更新的秘密,将查询的选择部分嵌入为注释:

UPDATE A 
    SET     items = X.c 
--select  Aitems, X.c,* 
FROM  tableA A 
INNER JOIN ( SELECT  tableB.c_id, COUNT(*) as c 
            FROM    tableB    
            LEFT JOIN tableC        
                ON tableB.c_id = tableC.c_id   
            WHERE tableC.c_id != tableC.c_id_update 
            GROUP BY tableB.bl_id ) X 
    ON A.id = X.c_id 

我还尝试确保显示我正在更新的字段以及我用于列表前面的新值的字段(如果select中有很多字段)。这样可以很容易地确定您认为您要更新的内容实际上是您想要的,但是从select关键字运行查询。