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

making where clause dynamic Expand / Collapse
Author
Message
Posted Wednesday, February 19, 2014 10:26 AM
Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: Sunday, August 17, 2014 3:50 AM
Points: 329, Visits: 858
Can we make where clause dynamic?

declare @hourly int

if @hourly = 1
--I want the where clause to say
TableA.LoadDateTime >= @TodaysDate
if @hourly = 0
--I want the where clause to say
convert(varchar(8),TableA.LoadDateTime,112) >= convert(varchar(8), @TodaysDate,112)


select col1, col2 from TableA
where TableA.LoadDateTime >= @TodaysDate
Post #1543126
Posted Wednesday, February 19, 2014 10:42 AM


SSC-Insane

SSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-Insane

Group: General Forum Members
Last Login: Yesterday @ 10:58 PM
Points: 21,755, Visits: 15,461
To get a dynamic where clause you would need to use dynamic sql and execute that sql string.

Or you could have both queries and an if else statement. Based on the conditions you provide, either one or the other query will be executed.




Jason AKA CirqueDeSQLeil
I have given a name to my pain...
MCM SQL Server


SQL RNNR

Posting Performance Based Questions - Gail Shaw
Posting Data Etiquette - Jeff Moden
Hidden RBAR - Jeff Moden
VLFs and the Tran Log - Kimberly Tripp
Post #1543135
Posted Wednesday, February 19, 2014 10:47 AM
Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: Monday, September 15, 2014 9:35 AM
Points: 1,116, Visits: 959
Will this help...
DECLARE @Hourly INT
SELECT @Hourly = 1
SELECT Col1,Col2 FROM TableA
WHERE
(CASE WHEN @Hourly = 1 THEN TableA.LoadDateTime
ELSE CONVERT(VARCHAR(8),TableA.LoadDateTime,112)
END) >=
(CASE WHEN @Hourly = 1 THEN @TodaysDate
ELSE CONVERT(VARCHAR(8),@TodaysDate,112)
END)

Post #1543138
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse