在Where语句中使用right函数更新

时间:2017-01-19 20:42:02

标签: sql-server

我正在尝试使用列的最后4位数字从另一个表更新一个表。以下是我所拥有的,显然是失败的。使用SQL 2012

UPDATE [DB].[dbo].[table1]
SET column1 = (SELECT table2.column1
                FROM table2
                WHERE (dbo.table2.column2 = dbo.table1.column2)
                 AND (dbo.table2.column3 = dbo.table1.column3) 
                 AND (dbo.table2.column4 = dbo.table1.column4) 
                 AND (dbo.table2.right(column5,4) = dbo.table1.right(column5,4))

1 个答案:

答案 0 :(得分:1)

在SQL Server中使用UPDATE执行JOIN的正确方法是:

UPDATE t1
SET t1.column1 = t2.column1 
FROM [DB].[dbo].[table1] t1
INNER JOIN dbo.table2 t2
    ON t2.column2 = t1.column2 COLLATE SQL_Latin1_General_CP1_CI_AS
    AND t2.column3 = t1.column3 COLLATE SQL_Latin1_General_CP1_CI_AS
    AND t2.column4 = t1.column4 COLLATE SQL_Latin1_General_CP1_CI_AS
    AND right(t2.column5,4) = right(t1.column5,4) COLLATE SQL_Latin1_General_CP1_CI_AS;