Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a table from a table variable

I have a SQL query that declares a table within it.

Declare @t table(tagname nvarchar(50), Value float, timestamp datetime)

I then insert some date into this table. Once this is done I want to update another table (already created) from @t.

Something along the lines of:

UPDATE Optimiser_tagData
SET Optimiser_tagData.value = @t.value
where Optimiser_tagData.tagName = @t.tagName

This obviously doesn't work and I get this error:

Must declare the scalar variable "@t"

I am sure I am missing something very easy but I can't quite figure it out.

like image 767
Silentbob Avatar asked Dec 01 '16 09:12

Silentbob


People also ask

How do you update a table based on values from another table?

We can update the table using UPDATE statement in SQL. The update statement is always followed by the SET command. The SET command is used to specify which columns and values need to be updated in a table.

Can you update a table variable in SQL?

t is an alias for @t. It's the same table. It is true you can't update a table variable directly using its variable name - you have to use an alias.

How do you update data in an existing table?

The UPDATE statement in SQL is used to update the data of an existing table in database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. UPDATE table_name SET column1 = value1, column2 = value2,...

How do you update a table with data from the same table in SQL?

Update With Select Sub Query: Same Table. Thus, the simplest and straightforward way to update values from one table to another table is to use the UPDATE FROM SELECT statement. By using UPDATE FROM, you can avoid the complicated ways like cursors, table data type, temp table, etc.


1 Answers

Your update statement should be like below. You have to apply Join between Table variable and Optimiser_tagData. And you should run update statement as a whole(Table variable declaration etc)

UPDATE Optimiser
    SET Optimiser.value = t.value
    from Optimiser_tagData Optimiser
    join @t t
    on Optimiser.tagName = t.tagName
like image 155
Tharunkumar Reddy Avatar answered Nov 14 '22 23:11

Tharunkumar Reddy