Saturday, January 22, 2011

Dynamic stored procedures without using IFs

Have you ever written a stored procedure like this?
create procedure GetProducts
   @id int
AS BEGIN
   if @id is not null
      SELECT *
      FROM Products
      WHERE id = @id
   ELSE
      SELECT *
      FROM Products
END
Here's a tip that DBAs and sql developers have known about for a while. You can shorten your query to this
create procedure MyProc
   @id int
AS
   SELECT *
   FROM Products
   WHERE (@id is null OR id = @id)
You should take care to examine the execution plan and make sure that it's not doing a table scan. Otherwise performance will suffer.

No comments:

Post a Comment