更新使用JOIN查找正确记录的表

时间:2012-12-21 17:03:00

标签: sql tsql

我正在尝试更新表格中的记录,要求我使用INNER JOIN来查找正确的记录。

   SELECT T2.*
   FROM Schema.Table2 T2 INNER JOIN 
     Schema.Table1 T1 ON T2.Key_Column = T1.Key_Column
   WHERE T2.ID = @ID AND T1.Code = '1'

尝试

UPDATE Schema.Table2 T2
SET T2.col1 = @Var1,
    T2.col2 = @Var2,
    T2.col3 = @Var3
WHERE T2.Key_Column = (SELECT T2.*
                       FROM Schema.Table2 T2 INNER JOIN 
                       Schema.Table1 T1 ON T2.Key_Column = T1.Key_Column
                       WHERE T2.ID = @ID AND T1.Code = '1')

请帮忙!

2 个答案:

答案 0 :(得分:4)

您不需要子选择:

UPDATE T2
SET T2.col1 = @Var1,
    T2.col2 = @Var2,
    T2.col3 = @Var3
FROM Schema.Table2 T2 INNER JOIN 
     Schema.Table1 T1 ON T2.Key_Column = T1.Key_Column
WHERE T2.ID = @ID AND T1.Code = '1'

答案 1 :(得分:3)

怎么样

UPDATE Schema.Table2
        SET
            col1 = @Var1,
            col2 = @Var2,
            col3 = @Var3
    FROM
            Schema.Table2 T2
        INNER JOIN 
            Schema.Table1 T1 
                ON T2.Key_Column = T1.Key_Column
    WHERE 
            T2.ID = @ID 
        AND 
            T1.Code = '1'