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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With