Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

Dynamic WHERE statement if stored procedure parameter is null Expand / Collapse
Author
Message
Posted Wednesday, July 10, 2013 6:05 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Wednesday, October 23, 2013 1:04 AM
Points: 10, Visits: 31
I have the stored procedure with @StartDate and @EndDate parameters
my WHERE statement is using those parameters to filter out data

WHERE condition1 and SomeDate >= @StartDate and SomeDate <= @EndDate and condition2

However when @StartDate or @EndDate is null or empty string then WHERE statement should look like below
WHERE condition 1 and condition2

I was trying already to do it with CASE of IF statement but without success so far.
Post #1472071
Posted Wednesday, July 10, 2013 6:51 AM


Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: Friday, June 27, 2014 8:03 AM
Points: 317, Visits: 1,079
Have you tried dynamic SQL?

Something like this:


declare @sql nvarchar(max),
@Startdate nvarchar(10),
@Enddate nvarchar(10);

set @sql = 'select * from #table1';
set @Startdate = '01/01/1900';
set @Enddate = '01/01/1900';

if @Startdate is not null and @Startdate <> ''
and @Enddate is not null and @Enddate <> ''
set @sql = @sql + ' where Startdate >= ''' + @Startdate + ''' and Enddate <= ''' +@Enddate + ''''

print @sql

exec sp_executesql @sql


Post #1472095
Posted Wednesday, July 10, 2013 7:44 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Wednesday, October 23, 2013 1:04 AM
Points: 10, Visits: 31
To be honest with you I don't like dynamic sql because of quotation marks '' which are making whole code harder to read :)
So Instead of this I developed something like this:
where condition1 and (SomeDate >= CASE WHEN @StartDate is null THEN SomeDate ELSE @StartDate END or SomeDate is null)
and (SomeDate <= CASE WHEN @EndDate is null THEN SomeDate ELSE @EndDate END or SomeDate is null) and condition2


Post #1472138
Posted Wednesday, July 10, 2013 7:49 AM


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: Yesterday @ 1:04 PM
Points: 13,086, Visits: 12,553
Oh be careful here Laurie. You suggested using dynamic sql which is a good choice here. However you committed a cardinal sin. You allowed for the parameters to be executed. This is now a sql injection vulnerability. You should instead use parameters to your dynamic sql.

Here is a full working example.

create table #table1
(
StartDate datetime,
EndDate datetime
)

insert #table1
select '1/15/1900', '2/1/1900'

declare @sql nvarchar(max),
@Startdate nvarchar(10),
@Enddate nvarchar(10);

set @sql = 'select * from #table1';
set @Startdate = '01/01/1900';
set @Enddate = '01/01/1901';

if @Startdate > '' AND @Enddate > ''
set @sql = @sql + ' where Startdate >= @Startdate and Enddate <= @Enddate'

print @sql

exec sp_executesql @sql, N'@Startdate datetime, @EndDate datetime', @Startdate = @Startdate, @Enddate = @Enddate

drop table #table1



_______________________________________________________________

Need help? Help us help you.

Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

Need to split a string? Try Jeff Moden's splitter.

Cross Tabs and Pivots, Part 1 – Converting Rows to Columns
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs
Understanding and Using APPLY (Part 1)
Understanding and Using APPLY (Part 2)
Post #1472145
Posted Wednesday, July 10, 2013 7:50 AM


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: Yesterday @ 1:04 PM
Points: 13,086, Visits: 12,553
phoenix_ (7/10/2013)
To be honest with you I don't like dynamic sql because of quotation marks '' which are making whole code harder to read :)
So Instead of this I developed something like this:
where condition1 and (SomeDate >= CASE WHEN @StartDate is null THEN SomeDate ELSE @StartDate END or SomeDate is null)
and (SomeDate <= CASE WHEN @EndDate is null THEN SomeDate ELSE @EndDate END or SomeDate is null) and condition2




This will work to a point. You will end up with some serious performance issues with this type of query though. Check out this article from Gail on the topic.

http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/


_______________________________________________________________

Need help? Help us help you.

Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

Need to split a string? Try Jeff Moden's splitter.

Cross Tabs and Pivots, Part 1 – Converting Rows to Columns
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs
Understanding and Using APPLY (Part 1)
Understanding and Using APPLY (Part 2)
Post #1472148
Posted Wednesday, July 10, 2013 3:38 PM
SSC-Addicted

SSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-Addicted

Group: General Forum Members
Last Login: Sunday, September 29, 2013 1:24 AM
Points: 429, Visits: 1,721
I use this syntax in my where clauses rather than case statements:


WHERE
((@StartDate IS NOT NULL AND StartDate >= @StartDate)
OR
(@StartDate IS NULL))
AND ((@EndDate IS NOT NULL AND EndDate <= @EndDate)
OR
(@EndDate IS NULL))


Post #1472383
Posted Thursday, July 11, 2013 7:02 AM


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: Yesterday @ 1:04 PM
Points: 13,086, Visits: 12,553
Steven Willis (7/10/2013)
I use this syntax in my where clauses rather than case statements:


WHERE
((@StartDate IS NOT NULL AND StartDate >= @StartDate)
OR
(@StartDate IS NULL))
AND ((@EndDate IS NOT NULL AND EndDate <= @EndDate)
OR
(@EndDate IS NULL))




You too might want to read that article from Gail. This type of approach can lead to really awful performance.


_______________________________________________________________

Need help? Help us help you.

Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

Need to split a string? Try Jeff Moden's splitter.

Cross Tabs and Pivots, Part 1 – Converting Rows to Columns
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs
Understanding and Using APPLY (Part 1)
Understanding and Using APPLY (Part 2)
Post #1472555
Posted Friday, July 12, 2013 12:59 AM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Tuesday, October 7, 2014 10:53 PM
Points: 3,421, Visits: 5,359
Sean Lange (7/10/2013)
phoenix_ (7/10/2013)
To be honest with you I don't like dynamic sql because of quotation marks '' which are making whole code harder to read :)
So Instead of this I developed something like this:
where condition1 and (SomeDate >= CASE WHEN @StartDate is null THEN SomeDate ELSE @StartDate END or SomeDate is null)
and (SomeDate <= CASE WHEN @EndDate is null THEN SomeDate ELSE @EndDate END or SomeDate is null) and condition2




This will work to a point. You will end up with some serious performance issues with this type of query though. Check out this article from Gail on the topic.

http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/


+1 to you Sean for the link to the bible on this topic.

I saw the subject of this thread and visited to make sure someone had already provided it.



My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
Post #1472875
Posted Saturday, July 13, 2013 12:47 AM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Monday, October 20, 2014 4:54 AM
Points: 1,921, Visits: 2,345
Thanks Sean for that link of Gail


_______________________________________________________________
To get quick answer follow this link:
http://www.sqlservercentral.com/articles/Best+Practices/61537/
Post #1473283
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse