Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a table variable in an "update from select" query?

I have this table variable declaration followed by a query:

DECLARE @CurrentItems TABLE
(
    ItemId uniqueidentifier,
    ItemUnits int
)

UPDATE U SET U.Units = U.Units + [@CurrentItems].ItemUnits
    FROM @CurrentItems CI INNER JOIN U ON U.UId=CI.ItemId;

And U is defined as follows:

CREATE TABLE [dbo].[U] (
    [UId]         UNIQUEIDENTIFIER UNIQUE NOT NULL,
    [Units]       INT DEFAULT ((0)) NOT NULL
);

When I run that in SQL Management Studio against SQL Server 2005 Express I get the following:

Msg 208, Level 16, State 1, Line 24

Invalid object name '@CurrentItems'.

I've already looked through this and this very similar questions but can't figure out how to solve the problem.

What's the actual problem and how do I resolve that?

like image 435
sharptooth Avatar asked Dec 16 '11 14:12

sharptooth


People also ask

Can we use SELECT statement in update query?

The UPDATE from SELECT query structure is the main technique for performing these updates. An UPDATE query is used to change an existing row or rows in the database. UPDATE queries can change all tables' rows, or we can limit the update statement affects for certain rows with the help of the WHERE clause.

How do you use variables in a SELECT statement?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.

How do you update a table with a query?

Open the database that contains the records you want to update. On the Create tab, in the Queries group, click Query Design. Click the Tables tab. Select the table or tables that contain the records that you want to update, click Add, and then click Close.


1 Answers

You've aliased @CurrentItems with CI so just use CI:

UPDATE U SET U.Units = U.Units + CI.ItemUnits
    FROM @CurrentItems CI INNER JOIN U ON U.UId=CI.ItemId;

Also take a look at your query you have something like U.UId = CU.ItemID. What is CU? You've made an alias for @CurrentItems with CI, so what is the purpose of CU? If this is a mistake, just a typo make sure you change any reference to CU with CI.

You also don't tell us what U is, I hope this is a valid table.

like image 124
JonH Avatar answered Oct 01 '22 04:10

JonH