2

I am trying to execute use Database_name command for switching on the particular database using below dynamic query. Query executed successfully but not switch the database.

declare @dbname varchar(50)='Database_name',
        @query nvarchar(200)
set @query='use '+@dbname+''
EXEC sp_executesql @query

1 Answer 1

1

Actually it works ,but the context will be gone as soon query ends

    declare @dbname varchar(50)='model',
            @query nvarchar(200)
    set @query='use '+@dbname+'
select db_name()'
    print @query
    exec (@Query)

The above query prints model as database name and context is reverted back..

More details on this here:Switching between databases with dynamic SQL

Session-level changes made in a sub-process (i.e. EXEC / sp_executesql) go away when that sub-process ends. This covers USE and SET statements as well as any local temporary tables created in that sub-process.

one more way is to change SSMS to results to text option,copy that and execute that

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.