Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update table using select statement results in sql server

I am trying to update a tabel where the value of field is equal the result of select statement. I have a table like this:

Type     Total#
A           4
B           8
C           1

I want to update the above table based the result of a select statement. Here is my code:

update MainTable
  set [Total#] = 
  (SELECT count(distinct r.[ID])as Type
  FROM dbo.TableA r left join
  dbo.TableB a
  on r.Post_ID = a.Post_ID
  where a.Status is null)

if i run the code as is, it is going to update all rows but i only want to update where Type from select statement is equal the Type from my MainTable. thanks

like image 941
moe Avatar asked Nov 21 '12 01:11

moe


People also ask

How do you update a table based on the SELECT statement?

After the SET keyword, we specified the column names to be updated, and also, we matched them with the referenced table columns. After the FROM clause, we retyped the table name, which will be updated. After the INNER JOIN clause, we specified the referenced table and joined it to the table to be updated.

Can I use SELECT with update?

The subquery defines an internal query that can be used inside a SELECT, INSERT, UPDATE and DELETE statement. It is a straightforward method to update the existing table data from other tables. The above query uses a SELECT statement in the SET clause of the UPDATE statement.

Can you use update and SELECT clause in one SQL?

You can't. There's no convention in a SQL UPDATE statement for returning data. And vice versa -- a SELECT statement doesn't write information to a table.


1 Answers

Give this a try,

UPDATE  x
SET     x.[Total#] = y.totalCount
FROM    MainTable x
        INNER JOIN
        (
            SELECT  [Type], COUNT(DISTINCT r.[ID]) totalCount
            FROM    dbo.TableA r
                    LEFT JOIN dbo.TableB a
                        ON r.Post_ID = a.Post_ID
            WHERE   a.STATUS IS NULL
            GROUP BY    [Type]
        ) y ON x.[Type] = y.[Type]

PS: when asking question like this, please add the structure of the table. It helps a lot.

like image 80
John Woo Avatar answered Oct 03 '22 08:10

John Woo