Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: how to use alias in update statement?

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?

like image 994
Steven Lemmens Avatar asked Aug 16 '17 14:08

Steven Lemmens


People also ask

Can we use alias in update statement SQL?

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.

Can we use subquery in 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 .

How do I use alias in SQL SELECT statement?

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.


2 Answers

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) 
like image 95
Zohar Peled Avatar answered Oct 19 '22 09:10

Zohar Peled


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) 
like image 1
Mat Avatar answered Oct 19 '22 09:10

Mat