troubleshooting Question

Optional Parameters in a SQL Server 2008 Stored Procedure

Avatar of Kaporch
Kaporch asked on
DatabasesMicrosoft SQL Server 2008
6 Comments1 Solution863 ViewsLast Modified:
My stored procedure is below.  I'm going to be needing to create several stored procedures with optional parameters.  If the parameters have a value, the value is being used in the WHERE clause.  If the parameters are NULL, then the field is ignored.  In the code below, I have a much smaller select statement for the 1st query because fewer tables are required in the join clause.  My question is, in 2008, is there any other way to accomplish the same thing as what I'm doing below, perhaps with less code?  Any examples welcome.
ALTER PROCEDURE SelectProducts
	-- Add the parameters for the stored procedure here
	@StartDate Date = Null,
	@Territory Varchar(20) = Null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
 
    -- Insert statements for procedure here
	--SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
	if @StartDate is not null and @Territory is null
	begin
	    Select '%' Union
		Select ProductName from ProductDim pd inner join DateDim dm
		on pd.ProductStartDateDimKey = dm.DateDimKey
		and dm.SQLDateStamp >= @StartDate
	end
	else
	begin
		if @StartDate is not null and @Territory is not null
		begin
		    Select '%' Union
			Select ProductName from ProductDim pd inner join DateDim dm
			on pd.ProductStartDateDimKey = dm.DateDimKey
			inner join ActivityProduct ap on ap.ProductDimKey = pd.ProductDimKey
			inner join SpendFact sf on sf.ActivityDimKey = ap.ActivityDimKey
			inner join GeographyDim gd on gd.GeographyDimKey = sf.GeographyDimKey
			and dm.SQLDateStamp >= @StartDate
			and gd.GeographyDimKey = @Territory
		end
	end
end
GO
ASKER CERTIFIED SOLUTION
Kaporch

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 6 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 6 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros