tags:

views:

238

answers:

5

Hey there,

I looking for a way to dynamicly add a filter to my statment without using dynamic SQL.

I want to select all computers from a table, but when I pass a computer id to the sp, I want to get only this computer.

Actually I try this on

DECLARE @ComputerFilter AS INT
DECLARE @ComputerID AS INT

SELECT Computername 
FROM   Computer
WHERE  (ComputerID = @ComputerID) OR (@ComputerFilter IS NULL))

But this is 100 times slow then this statment and tooks as long as SELECT * FROM Computer

SELECT Computername 
FROM   Computer
WHERE  ComputerID = @ComputerID

Is there a way to speed this statment up or is there any other way to solve this problem with one select und without dynamic sql?

+4  A: 

The easiest way would be to use IF statement.

IF @ComputerID IS NULL BEGIN
  SELECT Computername 
  FROM   Computer
END
ELSE BEGIN
  SELECT Computername 
  FROM   Computer
  WHERE  ComputerID = @ComputerID
END
Grzegorz Gierlik
This seems like the simplest option.
James Black
I agree IMO IF / ELSE is the best solution. @grzegorz, you here?! :)
htaler
Yes. I am. Since SO private beta.
Grzegorz Gierlik
A: 

SQL Server is often bad at optimising queries with an OR in the WHERE clause. Sometimes a UNION or UNION ALL is better. In your case, perform the @ComputerFilter IS NULL check first in in IF statement, and just do a SELECT without a WHERE if true...

David M
A: 

Do you have indexing on the table? That should help performance.

Bryan Denny
Yes, but the SQL Server only use it when I use the second statement. When I use my first stamtement with the "filter" the server makes an Index Scan.
Torben H.
+1  A: 

hi,

DECLARE @ComputerID AS INT

SET @ComputerID  = null -- fro all null or just id for one

SELECT Computername 
FROM   Computer
WHERE  ComputerID = ISNULL( @ComputerID, ComputerID  )

When you dont need

IordanTanev
Hi, nice solution, thank you. But the server makes an Index Scan too. Maybe I've to use two statement to get performance :(
Torben H.
A: 

There is no "one size fits all" query approach for this, there are subtle performance implications in how you do this. If you would like to go beyond just making the query return the proper answer, no matter how slow it is, look at this article on Dynamic Search Conditions in T-SQLby Erland Sommarskog

KM