我无法从查找表填充的查找光标中解析变量。
这与我之前的问题非常相似:
Dynamic MS SQL Variable Parsing incorrectly
但是现在我从查询表中提供了@tablename
和@columnname
,这导致我错过了列名周围的[
和]
。< / p>
DECLARE
@tableName SYSNAME,
@columnName SYSNAME,
@col2 SYSNAME,
@prompt SYSNAME,
@dynSQL varchar(MAX);
Declare cLookup CURSOR FOR
SELECT *
FROM LookupTbl
OPEN cLookup
FETCH NEXT FROM cLookup INTO @tableName, @columnName, @prompt
WHILE @@FETCH_STATUS = 0
BEGIN
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
Print 'Done with '+ @tableName
FETCH NEXT FROM cLookup
INTO @tableName, @columnName, @prompt
end
Close cLookup
Deallocate cLookup
查找表:
TableName ColumnName Prompt
A1-ExciseESN Anode Excise ESN (A1) NULL
A1-Excise DT Anode ExciseDate&Time(A1) NULL
A1-Excise DT-1 AnodeExcieDate&Time(A1)-1 NULL
StackFixture Stack Fixture NULL
见下面的输出。我错过了列名称周围的[
和]
。
输出:
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)
答案 0 :(得分:1)
有一个名为QUOTENAME
的函数可以完全执行此操作:
SET @dynSQL = REPLACE(
REPLACE(
@dynSQL
,'<tablename>'
, QUOTENAME(@tablename)
)
,'<columnname>',QUOTENAME(@columnname)
)
e.g。 select QUOTENAME('abc')
= '[abc]'