Dynamic SQL Where statements
I was trying to figure out how to use an if statement in the where clause of a sql statement. I came across this article that explains the use of coalesce. This is a great way to handle this.
http://www.sqlteam.com/item.asp?ItemID=2077
SELECT Cus_Name,
Cus_City,
Cus_Country
FROM Customers
WHERE Cus_Name = COALESCE(@Cus_Name,Cus_Name) AND
Cus_City = COALESCE(@Cus_City,Cus_City) AND
Cus_Country = COALESCE(@Cus_Country,Cus_Country)
Read the article to understand it. Basically if there is a value provided to the stored procedure then the comparison is done. If there is no value it essentially includes all records or (matches itself). I know, that doesn't make sense.
Thursday, May 24, 2007
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment