最近开始学习SQL并遇到了这个我无法找到解决方案的问题。 我正在尝试从多个数据库中收集数据并将其输出到单个表中。
源选择输出两列“acAcct”和“源db的名称”
的数据目标表的每个数据库都有“acAcct”和列。
我提出的事情:
DECLARE @command varchar(1000)
SET @command = 'IF ''[?]'' NOT IN (''[master]'', ''[model]'', ''[msdb]'', ''[tempdb]'')
INSERT INTO _utility.dbo.konta (acAcct, ''?'')
SELECT DISTINCT AC.acAcct
,AD.acName AS ''?''
from tHE_AcctTransItem as AC
LEFT JOIN vDE_SetAccount as AD
ON AC.acAcct = AD.acAcct'
EXEC sp_MSforeachdb @command
我为每个数据库收到此错误:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near 'name of DB'.
我想我错过了解析变量的内容:
INSERT INTO _utility.dbo.konta (acAcct, ''?'')
选择正常。
编辑:
结束了这个:
DECLARE @command varchar(1000)
SET @command = 'IF ''[?]'' NOT IN (''[master]'', ''[model]'', ''[msdb]'', ''[tempdb]'')
MERGE _utility.dbo.konta AS target
USING (SELECT DISTINCT AC.acAcct
,AD.acName AS [?]
from [?].dbo.tHE_AcctTransItem as AC
LEFT JOIN [?].dbo.vDE_SetAccount as AD
ON AC.acAcct = AD.acAcct) as source
ON (target.acAcct = source.acAcct)
WHEN MATCHED THEN UPDATE SET target.[?] = source.[?]
WHEN NOT MATCHED THEN
INSERT (acAcct, [?])
VALUES (source.acAcct, [?]);
'
EXEC sp_MSforeachdb @command
原始脚本仅填充第一列,而在其他列中出错。
答案 0 :(得分:0)
如果源数据库名称是列,则不应将其括在单引号中。方括号会更安全。
DECLARE @command varchar(1000)
SET @command = 'IF ''[?]'' NOT IN (''[master]'', ''[model]'', ''[msdb]'', ''[tempdb]'')
INSERT INTO _utility.dbo.konta (acAcct, [?])
SELECT DISTINCT AC.acAcct
,AD.acName AS [?]
from tHE_AcctTransItem as AC
LEFT JOIN vDE_SetAccount as AD
ON AC.acAcct = AD.acAcct'
EXEC sp_MSforeachdb @command