Cannot pass column name as parameter to sp_executesql

和自甴很熟 提交于 2019-12-05 12:07:22

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.

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