Search code examples
sql-serversetdeclare

SET inside UPDATE Statement in MSSQL not working


This is the query

DECLARE @tempvarA INT = 0
UPDATE Table1 SET @tempvarA = 1 + intColumn, columnA = @tempvarA

*intColumn is a column from Table1 It successfully executes the query but the value of columnA is 0 wherein @tempvarA was initially declared. Am I missing something here or does the value of @tempvarA only updates after the execution of the update statement?

I have tried the following:

DECLARE @tempvarA INT = 0
UPDATE Table1 SET @tempvarA = 1 + intColumn
UPDATE Table1 SET columnA = @tempvarA

It works but somehow I think there should be a more proper way to do it.


Solution

  • So if I understand your question correctly, first you want to declare a variable and set it with a value and then update the value of a column with that variable. Let's take it step by step:

    1)Declaring the variable:

    DECLARE @tempvarA INT;
    

    2)Setting the variable:

    SET @tempvarA = 1;
    

    3)Updating table with said variable:

    UPDATE Table1 SET columnA = @tempvar1;
    

    Just be careful though. The above will update ALL the values of columnA to that of tempvarA. If you want specific rows you will have to add a where clause in your UPDATE statement.