2015-09-04 66 views
0

這是我的SQL代碼。我已經嘗試過了2種方式無一不是給我的錯誤在數據庫名稱在批處理文件中傳遞數據庫名稱sql server

不正確的語法附近 'Intake_Bak_09_04_15_07_15'

方法1

INSERT INTO Inspectors (InspectorId, FirstName, LastName, UserName, ReplicationId) 
    SELECT 
     InspectorId, FirstName, LastName, UserName, ReplicationId 
    FROM N'$(oldDBName)'.dbo.Inspectors 

INSERT INTO MachineSettings (Name, Value) 
    SELECT Name, Value 
    FROM N'$(oldDBName)'.dbo.MachineSettings 
    WHERE Name = 'MachineId' 

方法2

DECLARE @InsSql VARCHAR(500), @MacSql VARCHAR(500) 

SET @InsSql = 'INSERT INTO Inspectors (InspectorId, FirstName, LastName, UserName, ReplicationId) SELECT InspectorId, FirstName, LastName, UserName, ReplicationId FROM N['$(oldDBName)'].dbo.Inspectors' 

PRINT @InsSql 

EXEC (@InsSql) 

SET @MacSql = 'INSERT INTO MachineSettings (Name, Value) SELECT Name, Value FROM N['$(oldDBName)'].dbo.MachineSettings WHERE Name = ''MachineId''' 

PRINT @MacSql 

EXEC (@MacSql) 

這是我正在使用的SQLCMD

for /f "tokens=1-4 delims=/ " %%i in ("%date%") do (
    set dow=%%i 
    set month=%%j 
    set day=%%k 
    set year=%%l 
    ) 
for /f "tokens=1-3 delims=: " %%i in ("%time%") do (
    set hour=%%i 
    set min=%%j 
    set sec=%%k 
    ) 

SQLCMD -S . -d Intake -i TransferSQL.Sql -b -v oldDBName=Intake_Bak_%month%_%day%_%year%_%hour%_%min% 

任何幫助表示讚賞。

在此先感謝

+1

的DBNAME不能爲VARCHAR。嘗試使用'[$(oldDBName)]'而不是'N ['$(oldDBName)']' – Paolo

+0

真棒,它工作。非常感謝你 –

回答

0

這是工作的語法,感謝保羅

INSERT INTO Inspectors (InspectorId, FirstName, LastName, UserName, ReplicationId) SELECT InspectorId, FirstName, LastName, UserName, ReplicationId FROM [$(oldDBName)].dbo.Inspectors 
INSERT INTO MachineSettings (Name, Value) SELECT Name, Value FROM [$(oldDBName)].dbo.MachineSettings WHERE Name = 'MachineId' 
相關問題