user7456202
user7456202

Reputation:

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

Upvotes: 2

Views: 5471

Answers (3)

Megha shah
Megha shah

Reputation: 232

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

Upvotes: 1

ahmed abdelqader
ahmed abdelqader

Reputation: 3560

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

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269773

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.

Upvotes: 0

Related Questions