Link to home
Start Free TrialLog in
Avatar of craigdev
craigdev

asked on

Why doesn't this work?

This query changes the database:
PRINT DB_ID()
USE DATABASE2
PRINT DB_ID()

The output is:
7
13

This query does not however:

PRINT DB_ID()
DECLARE @DBName NVARCHAR(10)
SET @DBName = 'DATABASE2'
DECLARE @SQL NVARCHAR(20)
SET @SQL = 'USE ' + @DBName  
PRINT @SQL
EXEC(@SQL)
PRINT DB_ID()

The output is
7
USE DATABASE2
7


The question is why? I would like a decent explanation please or solution to the problem :)

Thanks!


ASKER CERTIFIED SOLUTION
Avatar of appari
appari
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of craigdev
craigdev

ASKER

nice one thanks!