Thursday, September 10, 2009

SQL Shortcut Tip

In creating a SQL select statement to query some records from a table, it is pretty common to include WHERE clause - where you are limiting your selections by criterias specified.

Here is an example:

SELECT *
FROM Products
WHERE CategoryID = 5
The SQL statement above will return all Product records that are in Category 5.

Now, sometimes we want to use the condition only if it meets certain condition (like if the condition value is not empty or null).

So you SQL statement may look like this (assuming this is wrapped in a stored procedure) - where you want the stored procedure to return all Products if Category is not filtered:
  1. ALTER PROCEDURE [dbo].[GetProducts]
  2. @CategoryID int = NULL
  3. AS
  4.  
  5. IF (@CategoryID IS NULL)
  6. BEGIN
  7. SELECT *
  8. FROM dbo.Products
  9. END
  10. ELSE
  11. BEGIN
  12. SELECT *
  13. FROM dbo.Products
  14. WHERE CategoryID = @CategoryID
  15. END
Looks rather long isn't it? In LINQ this is a bit shorter, but still quite repetitive:
  1. var data;
  2. if (categoryId == 0)
  3. data = from row in db.Productselse
  4. data = from row in db.Products where CategoryID == categoryId
So how can we short-cut this into shorter statements that is elegant and still do the job well?
Like this:
  1. ALTER PROCEDURE [dbo].[GetProducts]
  2. @CategoryID int = NULL
  3. AS
  4.  
  5. SELECT *
  6. FROM dbo.Products
  7. WHERE (@CategoryID is NULL OR @CategoryID = 0) OR CategoryID = @CategoryID
In LINQ:
  1. var data = from row in db.Products
  2. where (CategoryID == categoryId || categoryId == 0)
By including the possibility of null or zero (or any default condition) in the WHERE clause means that the condition will be computed as well to produce the results. Got it?
-- read more and comment ...