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.
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.
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.
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,...
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.
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
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