1

I am trying to write a stored procedure which is taking two arguments to retrieve some data from customers table.

Below is the stored procedure, it does not retrieve any data, however when I just type the select query, it works.

Can somebody help me to see where is the problem?

CREATE PROCEDURE [dbo].[RecordsByColumnSearch]
    @field VARCHAR(50),
    @search VARCHAR(50)
AS
    SELECT *
    FROM Customers
    WHERE @field = @search

Executing this stored procedure like this:

EXEC dbo.RecordsByColumnSearch @field = CustomerID, @search = ALFKI;

does not return any data, while running this query does:

SELECT * 
FROM customers 
WHERE CustomerID = 'ALFKI';

Thank you in advance !

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Zoe
  • 21
  • 1
  • 1
  • 3

2 Answers2

6

You can't do what you want using regular SQL. You need dynamic SQL. I would recommend:

CREATE PROCEDURE [dbo].[RecordsByColumnSearch] (
    @field Varchar(50),
    @search Varchar(50)
) AS
BEGIN
    DECLARE @sql NVARCHAR(MAX);

    SET @sql = '
select c.*
from Customers c
Where @field = @search
';

    SET @sql = REPLACE(@sql, '@field', @field);
    EXEC sp_executesql @sql, N'@field nvarchar(50)', @search=@search;

END;

sp_executesql executes SQL statements and allows you to pass in parameters. That is the best way to pass parameters in. Unfortunately, that doesn't work for column names, so they still need to be passed in by munging the query string.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0
declare @field varchar(40)
declare @search varchar(40)

declare @sql nvarchar(max)

set @sql = 'select c.* from Customers c where '+@field+' = '''+@search +''''

exec sp_executesql @sql

For Using Stored Procedure

create proc recordsbycoulmnsearch
@field varchar(50),
@search varchar(50)
as
begin
declare @sql nvarchar(max)

set @sql = 'select c.* from customer c where '+@field+' = '''+@search+''''

exec sp_executesql @sql

end

exec recordsbycoulmnsearch 'Columnname','searchid'

Try this dynamic query..

Sarath
  • 61
  • 5
  • While this works, it leaves open the possibility of SQL injection. Using sp_executesql with the proper parameters will avoid that. – EzLo Jun 12 '18 at 14:17