8

I'm wondering about the following query :

   UPDATE statisticsTable
   SET Value = (select count(*) 
                FROM OtherTable o
                WHERE o.UserId = UserId ) <-- this is the part that concerns me
   WHERE id in (1,2,3) 

How does SQL Server know that the second "UserId" field comes from statisticsTable and not from OtherTable ? Why can't I give an alias to statisticstable like 'stat' to clarify where I want to get that UserId ? Or is there a way?

Burcin
  • 973
  • 1
  • 9
  • 25
Steven Lemmens
  • 1,441
  • 3
  • 17
  • 30
  • 1
    Is this working correctly? I usually do something like `WHERE o.UserId = statisticsTable.UserId` to be sure. – justiceorjustus Aug 16 '17 at 14:10
  • https://stackoverflow.com/questions/4981481/how-to-write-update-sql-with-table-alias-in-sql-server-2008 – Daniel Stackenland Aug 16 '17 at 14:11
  • Cant you have `UPDATE statisticsTable as s` and then have `WHERE o.UserID = s.UserId` in your subquery? I haven't tested this though. I've never had an UPDATE where a subquery has been neccessary. – Cenderze Aug 16 '17 at 14:34

3 Answers3

16

SQL Server supports updates using joins.
This means you can write your query like this:

UPDATE s
SET Value = d.NumOfRows
FROM statisticsTable s
INNER JOIN
(
     SELECT UserId, COUNT(*) As NumOfRows
     FROM OtherTable
     GROUP BY UserId
) d ON s.UserId = d.UserId
WHERE id in (1,2,3) 
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
1

Try this:

UPDATE s
   SET Value = x.cnt
from statisticsTable s
 outer apply (select count(*) as cnt
                FROM OtherTable o
                WHERE o.UserId = s.UserId ) x
WHERE s.id in (1,2,3) 
Mat
  • 213
  • 1
  • 11
0

An alias for the table you are updating is not allowed but you can use the table name in the normal way:

UPDATE statisticsTable
SET Value = (select count(*) 
            FROM OtherTable o
            WHERE o.UserId = statisticsTable.UserId ) 
WHERE id in (1,2,3)