Following is sample query.
CREATE PROCEDURE GetModel
(
@brandids varchar(100), -- brandid="1,2,3"
@bodystyleid varchar(100) -- bodystyleid="1,2,3"
)
AS
select * from model
where brandid in (@brandids) -- use a UDF to return table for comma delimited string
and bodystyleid in (@bodystyleid)
My requirement is that if @brandids or @bodystyleid is blank, query should return all rows for that condition.
Please guide me how to do this? Also suggest how to write this query to optimize performance.
You’ll need dynamic SQL or a split function for this anyway, since
IN ('1,2,3')is not the same asIN (1,2,3).Split function:
Code becomes something like:
(Note that I added a lot of NULLIF handling here… if these parameters don’t have a value, you should be passing NULL, not “blank”.)
Dynamic SQL, which will have much less chance of leading to bad plans due to parameter sniffing, would be:
Of course as @JamieCee points out, dynamic SQL could be vulnerable to injection, as you’ll discover if you search for dynamic SQL anywhere. So if you don’t trust your input, you’ll want to guard against potential injection attacks. Just like you would if you were assembling ad hoc SQL inside your application code.
When you move to SQL Server 2008 or better, you should look at table-valued parameters (example here).