sql >> Database teknologi >  >> RDS >> Sqlserver

Dynamisk MS SQL-variabel parsing forkert

  1. Brug de korrekte typer SYSNAME for indikatorer, NVARCHAR(MAX) for forespørgsel
  2. Brug REPLACE i stedet for at sammenkæde det vil det være meget nemmere at fejlfinde, især når du har brug for strenge bogstaver
  3. Overvej at bruge QUOTENAME funktion

Kode:

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

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] )


  1. Sådan udfyldes et tidsstempelfelt med det aktuelle tidsstempel ved hjælp af Oracle Sql Loader

  2. SQL WHERE betingelse er ikke lig med?

  3. Hent ConnectionString fra app.config i c#

  4. Sådan fungerer RADIANS() i MariaDB