Wednesday, November 18, 2009

Implimenting Optional arguments in SQL Server

CREATE PROCEDURE uspGetProductList
@Colour varchar = NULL,
@ProductCategoryID int = NULL
AS
BEGIN

SET NOCOUNT ON;

SELECT
ProductID,
ProductName,
ProductCode,
ProductDescription,
Colour,
ProductCategoryID
FROM Product
WHERE (@ProductCategoryID IS NULL OR ProductCategoryID = @ProductCategoryID)
AND (@Colour IS NULL OR Colour = @Colour)
-- if any one argument get no value, the variable's value will be NULL. The NULL value
-- always make the condition true
END

No comments:

Post a Comment