Sql-Server

我的查詢有什麼問題?

  • November 10, 2016

我知道這適用於名為 DB01_20161110 的數據庫:

ALTER AVAILABILITY GROUP AG1 ADD DATABASE DB01_20161110

我正在嘗試自動添加今天的日期:

DECLARE @DateString   AS VARCHAR(256)
SET @DateString =     cast(year(getdate()) as varchar(4)) 
+     right('0' + cast(month(getdate()) as varchar(2)), 2)
+     right('0' + cast(day(getdate()) as varchar(2)), 2)
DECLARE @DB AS VARCHAR (40)
SET @DB = 'DB01_' + @DateString

ALTER AVAILABILITY GROUP AG1 ADD DATABASE @DB
GO 

我得到:

Msg 102, Level 15, State 1, Line 8
Incorrect syntax near '@DB'

也試過:

DECLARE @DateString   AS VARCHAR(256)
SET @DateString =     cast(year(getdate()) as varchar(4)) 
+     right('0' + cast(month(getdate()) as varchar(2)), 2)
+     right('0' + cast(day(getdate()) as varchar(2)), 2)

ALTER AVAILABILITY GROUP AG1 ADD DATABASE 'DB01_' + @DateString
GO 

同樣的錯誤。

我對其他腳本使用相同的 DECLARE 部分,這樣就可以了。

有什麼建議嗎?

為此,您需要使用動態 SQL。以下範例將起作用(快速檢查以查看數據庫是否存在,您也可以添加其他檢查)。

DECLARE @DateString AS VARCHAR(256) ,
   @ExecuteText NVARCHAR(4000);
SET @DateString = CAST(YEAR(GETDATE()) AS VARCHAR(4)) + RIGHT('0'
                                                             + CAST(MONTH(GETDATE()) AS VARCHAR(2)),
                                                             2) + RIGHT('0'
                                                             + CAST(DAY(GETDATE()) AS VARCHAR(2)),
                                                             2);
DECLARE @DB AS VARCHAR(40);
SET @DB = 'DB01_' + @DateString;


IF EXISTS ( SELECT  name
           FROM    sys.databases
           WHERE   name = @DB )
   BEGIN
       SET @ExecuteText = N'ALTER AVAILABILITY GROUP AG1 ADD DATABASE ' + @DB
           + ';';
       EXEC sys.sp_executesql @ExecuteText;
   END;
ELSE
   BEGIN
       RAISERROR(N'Database: %s does not exist', 16, 1, @DB);
   END;
GO 

引用自:https://dba.stackexchange.com/questions/154850