我的动态变量分析问题不正确,我不知道解决方法。
以下是一个例子:
DECLARE @tableName varchar(20),
@columnName varchar(20),
@prompt varchar(20)
DECLARE @dynSQL varchar(500)
set @tableName = '[A1-ExciseESN]'
set @columnName = '[Anode Excise ESN (A1)]'
@dynSQL = 'INSERT INTO ' + @tableName +'
([trav num], '+@columnName+')
Select [trav num], '+@columnName+'
FROM [temprmi$] t1
PIVOT(min([Lvl1 Trace Data])
FOR [Prompt Text] IN ('+@columnName+'
)
) AS PVTTable
where '+@columnName+' is not null and [trav num] not in (select [trav num] from '+@tableName+')'
print @dynSQL
以下是print @dynSQL
INSERT INTO [A1-ExciseESN]
([trav num], [Anode Excise ESN (A)
Select [trav num], [Anode Excise ESN (A
FROM [temprmi$] t1
PIVOT(min([Lvl1 Trace Data])
FOR [Prompt Text] IN ([Anode Excise ESN (A
)
) AS PVTTable
where [Anode Excise ESN (A is not null and [trav num] not in (select [trav num] from [A1-ExciseESN])
我尝试了几种方法,但似乎无法使其发挥作用。 在此先感谢您的帮助!
答案 0 :(得分:2)
您已定义:
@columnName varchar(20),
但是你要分配:
set @columnName = '[Anode Excise ESN (A1)]'
columnname必须至少为varchar(23)。您使用的列名称长度为23个字符。
答案 1 :(得分:2)
SYSNAME
,为查询{/ li>使用NVARCHAR(MAX)
REPLACE
而不是连接它将更容易调试,尤其是当您需要字符串文字时QUOTENAME
功能代码:
DECLARE
@tableName SYSNAME,
@columnName SYSNAME,
@prompt VARCHAR(20),
@dynSQL NVARCHAR(MAX);
SET @tableName = QUOTENAME('A1-ExciseESN');
SET @columnName = QUOTENAME('Anode Excise ESN (A1)');
SET @dynSQL =
N'INSERT INTO <tableName>
([trav num], <columnName>)
Select [trav num], <columnName>
FROM [temprmi$] t1
PIVOT(min([Lvl1 Trace Data])
FOR [Prompt Text] IN (<columnName>)
) AS PVTTable
where <columnName> is not null
and [trav num] not in (select [trav num] from <tableName> )'
SET @dynSQL = REPLACE(REPLACE(@dynSQL, '<tableName>', @tableName),
'<columnName>', @columnName);
PRINT @dynSQL;
的 LiveDemo
强>
输出:
INSERT INTO [A1-ExciseESN]
([trav num], [Anode Excise ESN (A1)])
Select [trav num], [Anode Excise ESN (A1)]
FROM [temprmi$] t1
PIVOT(min([Lvl1 Trace Data])
FOR [Prompt Text] IN ([Anode Excise ESN (A1)])
) AS PVTTable
where [Anode Excise ESN (A1)] is not null
and [trav num] not in (select [trav num] from [A1-ExciseESN] )