sql use statement with variable

前端 未结 10 1309
花落未央
花落未央 2020-11-30 08:23

I\'m trying to switch the current database with a SQL statement. I have tried the following, but all attempts failed:

  1. USE @DatabaseName
  2. EXEC sp_sqlexe
10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 09:15

    Just wanted to thank KM for his valuable solution. I implemented it myself to reduce the amount of lines in a shrinkdatabase request on SQLServer. Here is my SQL request if it can help anyone :

    -- Declare the variable to be used
    DECLARE @Query varchar (1000)
    DECLARE @MyDBN varchar(11);
    -- Initializing the @MyDBN variable (possible values : db1, db2, db3, ...)
    SET @MyDBN = 'db1';
    -- Creating the request to execute
    SET @Query='use '+ @MyDBN +'; ALTER DATABASE '+ @MyDBN +' SET RECOVERY SIMPLE WITH NO_WAIT; DBCC SHRINKDATABASE ('+ @MyDBN +', 1, TRUNCATEONLY); ALTER DATABASE '+ @MyDBN +' SET RECOVERY FULL WITH NO_WAIT'
    -- 
    EXEC (@Query)
    

提交回复
热议问题