Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

Troubleshooting
Research
Professional Opinions
Ask a Question
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

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
Avatar of Kaporch
Kaporch

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

Commented:
This problem has been solved!
Unlock 1 Answer and 6 Comments.
See Answers