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?
One thing you must consider while using aliases in the UPDATE statement is if you are using an alias for table expressions then make sure to use it everywhere in the SQL UPDATE statement because all references to the table expression must be matched in the UPDATE statement.
Like SELECT , the UPDATE statement can have a subquery in several places or clauses. In an UPDATE , the two clauses in which subqueries are used most commonly are SET and WHERE . The SET clause is where we define the new value for the column being modified by the UPDATE .
Alias is used to give a temporary name(only for the duration of the query) to the column or table in order to make the column name or table name more readable. It does not change the name of the column permanently. Alias can be performed using the 'AS' keyword or without any keyword.
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)
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)
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