statement “USE @dbname” doesn't work, why? How to do that?

后端 未结 4 1755
轻奢々
轻奢々 2021-01-19 10:36

I\'ve got this t-sql snippet:

DECLARE @db_name varchar(255);
SET @db_name = \'MY_DATABASE\'; -- assuming there is database called \'my_database\'
USE @db_nam         


        
4条回答
  •  醉梦人生
    2021-01-19 10:42

    As you have noticed, the USE statement does not accept a variable as parameter. The only alternative that quickly comes to mind is quite crude and extremely error prone, but here you go:

    EXEC ('USE ' + @db_name + '
           SELECT * FROM some_table
           INSERT INTO some_table VALUES (1)')
    

    I hope that someone else can do better :-)

提交回复
热议问题