简体   繁体   中英

How to pass the SELECT statement as a parameter to stored procedure in SQL Server?

What is wrong with my code? I want to pass the select statement and where clause variable values:

ALTER PROC sp_ac_getItemLookupCode 
    @itemlookupcode varchar(20) = null,
    @select varchar(30)
AS
BEGIN
    SELECT DISTINCTT
        @select
    FROM
        [ReportHQMatajer].[dbo].[JFC_ItemDailySalesParent] pp
    WHERE 
        ItemLookupCode LIKE @itemlookupcode+'%' 
END

Above is my stored procedure. I execute the following code, but it returns the column Name only

sp_ac_getItemLookupCode @select='ItemLookupCode',@itemlookupcode=1

It is not returning all the values. It returns the column name as a result

Use Dynamic query via using SP_EXECUTESQL system stored proecures as next:-

ALTER PROC sp_ac_getItemLookupCode 
@itemlookupcode varchar(20)= null,
@select varchar(30)
AS
BEGIN
declare @Query nvarchar(2000)
set @Query = 
    'select distinct ' + @select + '
    FROM
        [ReportHQMatajer].[dbo].[JFC_ItemDailySalesParent] pp
    WHERE 
        ItemLookupCode like ''' + @itemlookupcode+ + '%'' '
exec sp_executesql @Query
END

If you want to pass column names as a parameter then you have to make your dynamic query, as next:-

Exec ('select distinct '+@select+'
    FROM
        [ReportHQMatajer].[dbo].[JFC_ItemDailySalesParent] pp')

If you want to pass column names (or table names or function names or the like), you need to use dynamic SQL:

ALTER PROC sp_ac_getItemLookupCode (
    @itemlookupcode varchar(20) = null,
    @select varchar(30)
) AS
BEGIN
    declare @sql = nvarchar(max);

    set @sql = '
select distinct @select
from [ReportHQMatajer].[dbo].[JFC_ItemDailySalesParent] pp
';

    set @sql = replace(@sql, '@select', @select);

    if (@itemlookupcode is not null)
    begin
        set @sql = @sql + 'where ItemLookupCode like ''' + @itemlookupcode + '%'''
    end;

    exec sp_executesql @sql;
END;

I added the functionality that if @itemlookupcode is NULL , then it returns all rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM