在批处理文件sql server中传递数据库名称

时间:2015-09-04 14:55:58

标签: sql-server batch-file

这是我的SQL代码。我尝试了两种方法,两者都在数据库名称

给我错误
  

“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 个答案:

答案 0 :(得分:0)

这是有效的语法,感谢Paolo

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'