I am using SQL Server 2008, and in my database I have a table called Student, with 3 columns name, lastname, year.
I want to give the user the opportunity to search students from that database by different attributes. I want to write one stored procedure, which will have 3 parameters (all the columns of Student) which could implement search in different ways.
If I write procedure this way:
Create Procedure ProcSearchStudents
@name nchar(20) = NULL,
@lastname nchar(20) = NULL,
@year int = NULL,
AS
if(@lastname = NULL)
BEGIN
Select *
from Student
where name = @name
and year = @year
END
if(@name = NULL)
BEGIN
Select *
from Student
where lastname = @lastname
and year = @year
END
if(@year = NULL)
BEGIN
Select *
from Student
where name = @name
and lastname = @lastname
END
...
...
GO
I have to write if() statement 3!(factorial) times. So, If I have 8 attributes, it will be almost impossible to write this.
Is there any other better way to do that, or a kind of engine, which can help me?
There’s a simple solution:
Although simple, this suffers from the problem of “parameter sniffing”. Basically, SQL Server creates a plan for the query based on the first search you run. This can be resolved by adding a query hint that forces SQL Server to re-create the query plan for every search:
If you do a lot of queries, the overhead of compiling a plan can become too high. In that case you have to resort to dynamic SQL. But that’s the answer to a different question.