Declare global variables for a batch of execution statements - sql server 2005

I have an SQL statement in which I am trying to update a table on a client machine. The sql statement is as follows:

    BEGIN TRANSACTION


    DECLARE @CreatedBy INT

    SELECT  @CreatedBy = [User_Id]
    FROM    Users
    WHERE   UserName = 'Administrator'

    --////////////////////////////////////////////////////////////////////
    --////////////////////////////////////////////////////////////////////

    PRINT @CreatedBy --(Works fine here and shows me the output)

    PRINT N'Rebuilding [dbo].[Some_Master]'
    ALTER TABLE [dbo].[Some_Master]
    ADD [CreatedBy] [BIGINT] NULL,
        [Reason] [VARCHAR](200) NULL
    GO

    PRINT @CreatedBy --(does not work here and throws me an error)


    PRINT N'Updating data in [Some_Master] table'
    UPDATE  Some_Master
    SET     CreatedBy = @CreatedBy

    COMMIT TRANSACTION

but I get the following error:

Must declare the scalar variable "@CreatedBy".

Now I noticed that if I write the Print statement on the alter command, it works fine and shows me its value, but if I try to print the value after the Alter command, it will give me the error above.

I do not know why??? please, help!

thank

+3
source share
3 answers

- GO, . GO , @CreatedBy .

GO.

+3

, GO.

+1

Delete the instruction "GO".

+1
source

Source: https://habr.com/ru/post/1748307/


All Articles