为什么下面的delayedexpansion循环脚本中的变量不能保持设置?
setlocal enabledelayedexpansion
set DB_LIST=(DB1 DB2)
for %%i in %DB_LIST% do (
set DATABASENAME=%%i
echo -- Backing Up Database %DATABASENAME% --
set DATESTAMP=%DATE:~-4%.%DATE:~3,2%.%DATE:~0,2%
set BACKUPFILENAME=F:\Backups\ScheduledBackups\%DATABASENAME%-%DATESTAMP%.bak
echo.
sqlcmd -E -S LiveDB2 -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = '%BACKUPFILENAME%' WITH DESCRIPTION = 'Full backup [%DATABASENAME%]', CHECKSUM, INIT, COMPRESSION, STATS"
)
endlocal
pause
我得到一个试图用BACKUP DATABASE DB1 TO DISK = ''
谢谢!
答案 0 :(得分:2)
那是因为您尝试使用百分号而不是感叹号来扩展变量。启用延迟扩展时,必须始终在for
循环内使用感叹号。
试试这个:
setlocal enabledelayedexpansion
set DB_LIST=(DB1 DB2)
for %%i in %DB_LIST% do (
set DATABASENAME=%%i
echo -- Backing Up Database !DATABASENAME! --
set DATESTAMP=%DATE:~-4%.%DATE:~3,2%.%DATE:~0,2%
set BACKUPFILENAME=F:\Backups\ScheduledBackups\!DATABASENAME!-!DATESTAMP!.bak
echo.
sqlcmd -E -S LiveDB2 -d master -Q "BACKUP DATABASE [!DATABASENAME!] TO DISK = '!BACKUPFILENAME!' WITH DESCRIPTION = 'Full backup [!DATABASENAME!]',
CHECKSUM, INIT, COMPRESSION, STATS")
endlocal
pause