Execute Query based on IF condition

Database
Fan

Execute Query based on IF condition

I need help to execute a query based on If Condition... I have a certain date range in my source .. I need to execute queries based on a date range. i.e..
declare @date
if @date='x'
execute query 1
if @date
execute query 2.

please help
4 REPLIES
Fan

Re: Execute Query based on IF condition

Need some response. please help

Junior Contributor

Re: Execute Query based on IF condition

You should write a Stored Procedure for this.

If all those queries return compatible columns a Macro might work, too:

replace macro xxx (indate date) as
(
select ....
where indate = '1st date'

union all

select ....
where indate = '2nd date'

union all
...
)

Fan

Re: Execute Query based on IF condition

I shouldnt write stored procedure and macros.. I dont have access.. any other way to acheive it ?

Enthusiast

Re: Execute Query based on IF condition

If you are using BTEQ, use dummy query to check condition:

/
/*Below statement uses sys calendar table as dummy to check condition – if the condition is true, then the SQL returns 1 , else no result */

SELECT TOP 1 1 FROM SYS_CALENDAR.CALENDAR
WHERE Calendar_Date = 'Date 1'

/* Activity count checks number of statement affected by last SQL, if condition is true then Acitivity count > 0, so delete would be skipped */

.IF ACTIVITYCOUNT= 0 THEN .GOTO QUERY2;

Query 1;

.LABEL QUERY2;

SELECT TOP 1 1 FROM SYS_CALENDAR.CALENDAR
WHERE Calendar_Date = 'Date 2'

IF ACTIVITYCOUNT= 0 THEN .GOTO QUERY3;

Query 2;

/*Likewise continue as many times as you need */