How to update a table based on a query returning any rows

-- -- 957 Reputation points
2023-01-23T11:52:45.15+00:00

Hi

We have a select query on a table. Based on if the query returns any rows, how can we update a column in a second table?

Thanks

Regards

SQL Server | Other
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2023-01-23T12:13:20.2233333+00:00

    For example, you can do something like this:

    if exists( select * from Table1 ) -- if the first query returns any row
       update Table2 -- update a column in the second table
       set SomeColumn = 'some value' 
    

    It depends on different aspects of your problem.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2023-01-24T02:27:23.5933333+00:00

    Hi @-- --

    If what you need is that a change to Table 1 will update Table 2, you can use triggers to solve it. But here, all you want is to update Table 2 as soon as the contents of the table are retrieved.

    You can try the method provided by Viorel, you can add the conditions you want in the query in parentheses after exists.

    Best regards,

    Percy Tang

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.