-1

我想使用 sqlcmd 传入一个日期变量并做一个检查条件,如果没有传入日期,则将该变量设置为 getdate()。谁能给我建议?谢谢你。下面是我的 sql 脚本。( getdate() 部分应该修改)

--Declare variable to store back up file location
DECLARE @DBBackupFile as nvarchar(128);

SET @DBBackupFile = N'C:\sqlbackup\MOL_POSHistory\MOL_POSHistory_backup_' + convert(varchar(12),(year(GETDATE()) * 10000) + (month(GETDATE()) * 100) + Day(GETDATE()) -4 ) + N'0201.bak';

--Retrive the Logical file name of the database from backup.
RESTORE FILELISTONLY
FROM DISK = @DBBackupFile
GO

--Make Database to single user Mode
ALTER DATABASE [MOL_POSHistory]
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE

--Restore Database
DECLARE @DBBackupFile as nvarchar(128);

SET @DBBackupFile = N'C:\sqlbackup\MOL_POSHistory\MOL_POSHistory_backup_' + convert(varchar(12),(year(GETDATE()) * 10000) + (month(GETDATE()) * 100) + Day(GETDATE()) -4 ) + N'0201.bak';

USE master;

RESTORE DATABASE [MOL_POSHistory] FROM DISK = @DBBackupFile WITH FILE = 1,

MOVE N'MOL_POSHistory' TO N'D:\SQLData01\MOL_POSHistory.mdf',

MOVE N'MOL_POSHistory_log' TO N'F:\SQLLog\MOL_POSHistory.ldf',

NOUNLOAD, REPLACE, STATS = 10

--Set database to multi user mode
ALTER DATABASE [MOL_POSHistory] SET MULTI_USER
GO
4

1 回答 1

1

您需要使用 –v 参数像这样调用 SQLCMD:

// Date format is YYYYMMDD

sqlcmd -S YOUR_SERVER -v inputDate="20010101" -i "YOUR_INPUT_FILE" -E

您可以访问 SQLCMD 传入的参数(inputDate在此示例中),如下所示:

DECLARE @inputDate NVARCHAR(50)

DECLARE @date DATETIME



SET @inputDate = '$(inputDate)'



IF (LEN(ISNULL(@inputDate, '')) = 0) BEGIN

        SET @date = GETDATE()

       PRINT 'Using default date'

END

ELSE BEGIN

        SET @date = @inputDate

        PRINT 'Using varaible date'

END
于 2012-06-27T05:38:22.277 回答