Cannot pass column name as parameter to sp_executesql

淺唱寂寞╮ 提交于 2019-12-22 08:15:02

问题


I'm having trouble executing the below piece of code, it's giving me an error as below:

Msg 102, Level 15, State 1, Line 3 Incorrect syntax near '@ST'.

I can try implementing the login using dynamic SQL, but wanted to try the sp_executesql method. Please let me know if I'm having some syntax error or I'm not supposed to pass table names as parameters?

DECLARE @SQL NVARCHAR(4000)= '';
SET @SQL = N'--INSERT INTO #missingkeys ( SOURCE_KEY,[ROWCOUNT] ) 
SELECT  S.[SOURCE_KEY], COUNT(1) AS [ROWCOUNT] FROM (SELECT DISTINCT   @SK AS [SOURCE_KEY] 
FROM [PDA].@ST ) AS S
LEFT JOIN [PDA].@MT   AS T 
ON T.[SOURCE_KEY] = S.[SOURCE_KEY]
GROUP BY S.[SOURCE_KEY]';
DECLARE @SOURCETABLE NVARCHAR(255)= 'FACT';
DECLARE @SOURCE_KEY NVARCHAR(255)= 'KEY', @MAP_TABLE NVARCHAR(255)= 'DimMap';
EXEC sp_executesql
 @SQL,
 N'@SK nvarchar(255), @ST nVARCHAR(255), @MT nVARCHAR(255)',
 @SK = @SOURCE_KEY,
 @ST = @SOURCETABLE,
 @MT = @MAP_TABLE;

回答1:


You can't have columns as parameters, same for any object name (table, stored procedure, ...).

You will have to make the statement dynamic, i.e. format the column name in the SQL string:

SET @SQL = 
    N'SELECT '+
        'S.[SOURCE_KEY],'+
        'COUNT(1) AS [ROWCOUNT] '+
     'FROM ('+
         'SELECT DISTINCT '+
             QUOTENAME(@SK)+' AS [SOURCE_KEY] '+
             '...'; -- the rest of your statement

PS: Use QUOTENAME to escape object names to avoid SQL Injection.




回答2:


You can pass tables if you write the data to an identical user-defined table type. The parameter must be READONLY:

CREATE TYPE [dbo].[t] AS TABLE([a] [int] NOT NULL PRIMARY KEY CLUSTERED)
create table #t (a int)
insert into #t values (1), (2), (3)
exec sp_executesql N'select * from #t'
declare @t t
insert into @t select a from #t
exec sp_executesql N'Select * from @p1', N'@p1 t readonly', @t


来源:https://stackoverflow.com/questions/48335319/cannot-pass-column-name-as-parameter-to-sp-executesql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!