Link to home
Start Free TrialLog in
Avatar of dkilby
dkilbyFlag for Canada

asked on

sql stored procedure + if statement

is it possible to have an if statement in a query - so if a value of a variable is 'yes' for example a line is added to the query ?

ie

@Variable

select * from table
where date >= getDate()
if @Variable = 'yes' then add this line of code to the query
and customerActive = 1
Avatar of ste5an
ste5an
Flag of Germany image

hmm..

USE AdventureWorks2014;
GO

DECLARE @AllRows BIT = 0;

SELECT	*
FROM	sys.tables T
WHERE	T.name LIKE 'Person%' OR @AllRows = 1;

SET @AllRows = 1;

SELECT	*
FROM	sys.tables T
WHERE	T.name LIKE 'Person%' OR @AllRows = 1

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If @variable could ever possibly be null rather than no:

select * from table
where date >= getDate() and (@variable is null or @variable = 'n' or customerActive = 1)
Avatar of dkilby

ASKER

thank you, there is chance of a null value so this worked perfectly