T-SQL: Dynamic Where clause in normal SQL statement

Posted by Torben H. on Stack Overflow See other posts from Stack Overflow or by Torben H.
Published on 2010-03-24T14:13:26Z Indexed on 2010/03/24 14:23 UTC
Read the original article Hit count: 322

Filed under:

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?

© Stack Overflow or respective owner

Related posts about tsql