Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Parsing Variabel MS SQL Dinamis salah

  1. Gunakan jenis yang benar SYSNAME untuk pengidentifikasi, NVARCHAR(MAX) untuk permintaan
  2. Gunakan REPLACE alih-alih menggabungkannya, akan lebih mudah untuk men-debug terutama ketika Anda membutuhkan literal string
  3. Pertimbangkan untuk menggunakan QUOTENAME fungsi

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

Keluaran:

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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Instalasi SQL Server 2017

  2. cara memasukkan ip di server tertaut kueri

  3. Pengenalan SQL Server 2017

  4. Memasang Instance Failover Cluster SQL Server – Bagian 1

  5. Bagaimana mengkonversi database Visual Foxpro ke database SQL Server