0

I'm having trouble parsing a variable from a lookup cursor populated by a lookup table.

It is very similar to my previous question here:

Dynamic MS SQL Variable Parsing incorrectly

But now I'm supplying the @tablename and @columnname from a lookup table, which is causing me to miss the [ and ] around the column names.

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

Lookup Table:

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

See output below. I am missing the [ and ] around the column names.

Output:

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)
Community
  • 1
  • 1
TangoAlee
  • 1,260
  • 2
  • 13
  • 34

1 Answers1

1

There is a function called QUOTENAME which will do exactly that:

SET @dynSQL = REPLACE(
               REPLACE(
                @dynSQL
                ,'<tablename>'
                , QUOTENAME(@tablename)
                )
              ,'<columnname>',QUOTENAME(@columnname)
               )

e.g. select QUOTENAME('abc') = '[abc]'

QUOTENAME (Transact-SQL)

Sam Cohen-Devries
  • 2,025
  • 2
  • 18
  • 35