Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UPDATE row when matching row exists in another table

Tags:

sql

tsql

I need to update a field on a table to be true only if a matching row exists in another table, for all the rows where the column is currently null in the main table.

This is a description of what I want to achieve:

UPDATE [LenqReloaded].[dbo].[Enquiry] A 
SET [ResponseLetterSent] = 1
WHERE [ResponseLetterSent] IS NULL
   AND EXISTS
       (
           SELECT * FROM [LenqReloaded].[dbo].[Attachment] B 
           WHERE A.[EnquiryID] = B.[EnquiryID]
       )

This isn't syntactically correct.

I can't code it via an IF EXISTS... statement because I don't have the [EnquiryID] without reading the data from the table.

How should I format my UPDATE statement?

like image 657
Val M Avatar asked Dec 10 '09 15:12

Val M


People also ask

How do you UPDATE a table based on values from another table?

In this article, we will see, how to update from one table to another table based on ID match. We can update the table using UPDATE statement in SQL. The update statement is always followed by the SET command. The SET command is used to specify which columns and values need to be updated in a table.

Can we use UPDATE with WHERE clause?

Notice the WHERE clause in the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated!


2 Answers

You weren't far off...

UPDATE A
SET A.[ResponseLetterSent] = 1 
FROM [LenqReloaded].[dbo].[Enquiry] A
WHERE A.[ResponseLetterSent] IS NULL 
    AND EXISTS ( SELECT * FROM [LenqReloaded].[dbo].[Attachment] B WHERE A.[EnquiryID] = B.[EnquiryID] )
like image 112
AdaTheDev Avatar answered Sep 23 '22 11:09

AdaTheDev


You need to use a join in your update:

UPDATE [LenqReloaded].[dbo].[Enquiry] SET [ResponseLetterSent] = 1 
FROM [LenqReloaded].[dbo].[Enquiry] A 
join [LenqReloaded].[dbo].[Attachment] B on A.[EnquiryID] = B.[EnquiryID] 
WHERE A.[ResponseLetterSent] IS NULL
like image 45
Matt Wrock Avatar answered Sep 22 '22 11:09

Matt Wrock