5

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

1
  • what are the table structures for tableA and tableB? Commented Nov 21, 2012 at 2:02

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Give an alias to your MainTable and you can use it in the subquery:

update MainTable mt
   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
                      and a.AType = mt.AType )
 where mt.AType = @Value

2 Comments

thanks but i am getting this error: Must declare the scalar variable "@Value".
@moe The shown query is an example, if you don't need the where, remove it, or adjust the @value to a real value you want to filter with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.