1

How can pass two SQL parameters in a stored procedure to a query string in the WHERE clause? The issue I'm having is in the @iField. If I remove that and replace with InfoID LIKE '%' + @iSearch + '%', it works, but I need to add the @iField.

WHERE CustomerID = @CustomerID AND @iField LIKE '%' + @iSearch + '%'

3 Answers 3

1

As far as you are allready using a procedure

Declare @Query nvarchar(max)
Select @Query=
'
Select * from dbo.Invoice
WHERE CustomerID = '+Cast(@CustomerID as Varchar(20)) 
+' AND ['+ @iField +'] LIKE ''%' + @iSearch + '%''
'

--Print @Query
Exec(@Query)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help. Using your suggestion I'm getting an Invalid column name ''+ @iField +'' error.
@g_shockTan just copying my post I get results print will show e.g. Select * from dbo.Invoice WHERE CustomerID = 1 AND [BillNr] LIKE '%aus%' Try with print instead of Exec, might be missing quotation ...
0

T-SQL doesn't allow you to substiute variables for object names (it would be handy though, wouldnt' it). Two options really:

1) Use dynamic SQL e.g. sp_executesql (http://www.techrepublic.com/blog/datacenter/generate-dynamic-sql-statements-in-sql-server/306)

or

2) Use IF...ELSE e.g.

IF @iField = 'InfoId'
     SELECT ...
     WHERE CustomerID = @CustomerID AND InfoId LIKE '%' + @iSearch + '%'
ELSE IF @iField = '<some other field>'
     SELECT ...
     WHERE CustomerID = @CustomerID AND <some other field> LIKE '%' + @iSearch + '%'
etc.

3 Comments

Basically I would like to know if it's possible to write the WHERE clause as: WHERE @iField LIKE '%' + @iSearch + '%'.
No you can't substitue column names, table names, procedure names etc. with variable names unless you build a sql string and execute it dynamically as in (1) above.
Very interesting article. Thank you for the link.
0

If I understand correctly, you are simply trying to limit the like operator to a specific column?

declare @yourTable table (i int, FirstName varchar(10), LastName varchar(10))
insert into @yourTable
    select 1, 'john', 'doe' union all
    select 2, 'jane', 'doe';


declare @iField varchar(10),
        @iSearch varchar(10);


select  @iField = 'FirstName',
        @iSearch = 'j'


select  *
from    @yourTable
where   (@iField = 'FirstName' and FirstName like '%' + @iSearch + '%') or
        (@iField = 'LastName' and LastName like '%' + @iSearch + '%')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.