I’m writing an sql statement (see below) which compares 2 serial numbers on 2 different tables, table1 and table2. If the serial number exists then i want another column on table1 to be updated with a ‘yes’ and if the serial number in table1 does not exist in table2 I want to update with a ‘no’
My current sql statement works perfectly and fills the column with ‘yes’ when necessary. My problem is that instead of placing a ‘no’ when the serial number doesnt exist, instead it updates to NULL. My where statement is important as I only want to compare serial numbers on both tables where the date and install match up in both tables. I do not want to compare every row. Thanks
UPDATE dbo.table1
SET [Match] = CASE WHEN dbo.table2.[Serial Number] IS NOT NULL
THEN 'yes' ELSE 'no' END
FROM dbo.table1 LEFT OUTER JOIN dbo.table2
ON dbo.table2.[Serial Number] = dbo.table1.[Serial Number]
Where dbo.table1.[Date] = 'JAN11' AND
dbo.table1.[Install] = 'new' AND
dbo.table2.[Date] = 'JAN11' AND
dbo.table2.[Install] = 'new'
Put the WHERE conditions to JOIN’s condition:
@Baz1nga:
The WHERE causes the rows to be filtered out, hence the setting of value(s) are not being assigned back to table1.
Try this:
Output: