SQL Update和Join更新错误记录

时间:2017-06-08 15:15:53

标签: sql sql-server join

我正在尝试在SQL Server上使用带有JOIN的UPDATE语句。

如果我运行下面的SELECT语句,则返回42行。

int8_t

但是当我在更新语句(下面)中使用它时,查询会更新44条记录。

SELECT * FROM [dbo].[Imported] i 
inner join [DaisyCompare].[dbo].[Baseline] b
on 
b.[CLI]=i.[CLI] AND 
b.[Quantity]=i.[Quantity] AND 
b.[UnitCost]=i.[UnitCost] AND 
b.[TotalCost]=i.[TotalCost] AND 
b.[Description]=i.[Description] 

WHERE b.[CLI]=i.[CLI] AND 
b.[Quantity]=i.[Quantity] AND 
b.[UnitCost]=i.[UnitCost] AND 
b.[TotalCost]=i.[TotalCost] AND 
b.[Description]=i.[Description]

大概我的语法错了,但我不知道在哪里。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

您可以使用别名来选择要更新的连接表

UPDATE b
SET Disposition = 'Match'
FROM [dbo].[Imported] i 
inner join [DaisyCompare].[dbo].[Baseline] b
on 
b.[CLI]=i.[CLI] AND 
b.[Quantity]=i.[Quantity] AND 
b.[UnitCost]=i.[UnitCost] AND 
b.[TotalCost]=i.[TotalCost] AND 
b.[Description]=i.[Description] 

答案 1 :(得分:0)

您可以将常规更新语法与连接一起使用,并且只需要连接谓词,where子句是多余的:

UPDATE b
SET Disposition = 'Match'
FROM [dbo].[Imported] i 
INNER JOIN [DaisyCompare].[dbo].[Baseline] b
ON
b.[CLI]=i.[CLI] AND 
b.[Quantity]=i.[Quantity] AND 
b.[UnitCost]=i.[UnitCost] AND 
b.[TotalCost]=i.[TotalCost] AND 
b.[Description]=i.[Description] 

答案 2 :(得分:0)

"存在"绝对是个问题。你可以使用IN和引用主键是什么。

update [DaisyCompare].[dbo].[Baseline]

set Disposition = ('Match')

where [DaisyCompare].[dbo].[Baseline].[PrimaryID] IN
 (
SELECT [b.PrimaryID] FROM [dbo].[Imported] i 
inner join [DaisyCompare].[dbo].[Baseline] b

on 
b.[CLI]=i.[CLI] AND 
b.[Quantity]=i.[Quantity] AND 
b.[UnitCost]=i.[UnitCost] AND 
b.[TotalCost]=i.[TotalCost] AND 
b.[Description]=i.[Description] 

WHERE b.[CLI]=i.[CLI] AND 
b.[Quantity]=i.[Quantity] AND 
b.[UnitCost]=i.[UnitCost] AND 
b.[TotalCost]=i.[TotalCost] AND 
b.[Description]=i.[Description] )