SQL Server - CASE on where clause - sql

I'm working on a stored procedure that is a select query. Under the WHERE clause I am filtering the return results to return only if there is a PageTitle= 'STA'
Here is am example of my query :
#InputCountryId INT,
#InputIndustryId INT
AS
BEGIN
SELECT
r.IdCountry,
r.IdIndustry,
r.PageTitle,
r.IndustryName
From dbo.Reports r
WHERE
r.IdCountry = #InputCountryId
r.IdIndustry = #InputIndustryId
r.PageTitle = 'STA'
END
The ending condition r.PageTitle I would like it to be applied ONLY IF InputCountry = 1 if not; do not include the filter.
I've attempted this by including a CASE. I am having a syntax error any time I try and introduce this case. Is this something that is possible? Am I implementing it incorrectly?
Here is an example of the stored proc with the CASE included.
#InputCountryId INT,
#InputIndustryId INT
AS
BEGIN
SELECT
r.IdCountry,
r.IdIndustry,
r.PageTitle,
r.IndustryName
From dbo.Reports r
WHERE
r.IdCountry = #InputCountryId
r.IdIndustry = #InputIndustryId
CASE WHEN #InputCountryId = 1 THEN
r.PageTitle = 'STA'
END
END

Try it this way:
WHERE
r.IdCountry = #InputCountryId and
r.IdIndustry = #InputIndustryId and
(#InputCountryId <> 1 or r.PageTitle = 'STA')

You dont need case statement. You can use OR clause
WHERE
r.IdCountry = #InputCountryId
r.IdIndustry = #InputIndustryId
(#InputCountryId != 1 OR r.PageTitle = 'STA')
this only filters PageTitle with STA when InputCountry is 1

I can't test with your data, but here is a CASE in a WHERE clause that works.
DECLARE #Variable INT = 3
SELECT GETDATE()
WHERE 1 =
CASE
WHEN #Variable = 1 THEN 1
WHEN #Variable = 3 THEN 1
WHEN #Variable = 5 THEN 1
ELSE 0
END

Related

Reusing Value of a subquery in Else clause

is there any way i can use the value of X in the if clause in the else clause
if #bid_value>(SELECT MAX(bid_value) AS X FROM dbo.auctionDetails WHERE status = 0 AND vehicle_id=#vid GROUP BY vehicle_id)
BEGIN
//some code
END
ELSE IF X=NULL
BEGIN
//some code
END
Why don't you create a var for the value?
DECLARE #maxValue INT
SELECT #maxValue = MAX(bid_value)
FROM dbo.auctionDetails
WHERE status = 0 AND vehicle_id = #vid
IF (#bid_value > #maxValue)
BEGIN
// some code
END
ELSE IF (#maxValue IS NULL)
BEGIN
// some code
END
A comment about how you are getting the MAX value: As you are filtering by vehicle_id = #vid, you don't need GROUP BY clause since you will get results for only one value of vahicle_id
You would typically assign the results of the query to a variable.
If you are running SQL Server:
DECLARE #max_bid_value INT;
SELECT #max_bid_value = MAX(bid_value)
FROM dbo.auctionDetails
WHERE status = 0 AND vehicle_id = #vid;
IF #bid_value > #max_bid_value
BEGIN
//some code
END
...
Note that I removed the GROUP BY clause from the original query - I think that this makes it clearer that it should always return a scalar value.
Note that if you want to check if a variable is null, you need #bid is null rather than #bid = null.
Your query should be like below :
DECLARE #X INT
SET #X = (SELECT MAX(bid_value) AS X FROM dbo.auctionDetails WHERE status = 0 AND vehicle_id=#vid);
IF #bid_value>#MAX
BEGIN
//some code
END
ELSE IF X=NULL
BEGIN
//some code
END

Apply IF conditional at the end of the query

I'm new in sql server and I have WHERE clause like this:
WHERE[D].[IsLocked] = 0
AND(#StartDate IS NULL OR ISNULL([TA].[ModifiedDate], [TA].[CreationDate]) >= #StartDate)
AND(#EndDate IS NULL OR ISNULL([TA].[ModifiedDate], [TA].[CreationDate]) <= #EndDate)
AND((CASE WHEN[T].[TaskStatusId] = '09E02513-00AD-49E3-B442-A9ED2833FB25'
THEN 1 ELSE 0 END) = #Completed)
AND((#FilterEmpKey IS NULL AND[TA].[EmpKey] = #CurrentEmpKey)
OR (ISNULL([TA].[ModifiedAssignedBy], [TA].[AssignatedBy]) = #FilterEmpKey
AND[TA].[EmpKey] = #CurrentEmpKey))
But now I want to add if conditional in order to add more filters at the end of query like:
IF(#FilterEmpGuid IS NOT NULL)
AND[TA].[EmpKey] = #CurrentEmpKey
AND[TA].[AssignatedBy] = #CurrentEmpKey
AND[TA].[EmpKey] = #FilterEmpKey
But I get:
The multi-part identifier [TA].[EmpKey] could not be bound
What am I doing wrong?
IF conditionals are only for use outside sql queries, such as in procedures etc.
In a query itself you are limited to AND, OR and CASE statements, so you will need to rewrite your IF conditional for this:
AND (#FilterEmpGuid IS NULL
OR (
[TA].[EmpKey] = #CurrentEmpKey
AND[TA].[AssignatedBy] = #CurrentEmpKey
AND[TA].[EmpKey] = #FilterEmpKey
))
You could move the additional filter options into a scalar function.
If you know the additional fields that may be filtered, you may be able to get away with something like:
CREATE FUNCTION dbo.ExtendFilter(
#column_value VARCHAR(50), #param_value VARCHAR(50)
)
RETURNS BIT
AS
BEGIN
DECLARE #return BIT = 1; -- default RETURN to 1 ( include ).
IF ( NULLIF( #param_value, '' ) IS NOT NULL )
BEGIN
-- compare the column's value to the param value
IF ( #column_value <> #param_value )
SET #return = 0; -- don't include this record.
END
RETURN #return;
END
GO
And then use it like:
WHERE
{ other WHERE stuff }
AND dbo.ExtendFilter( [TA].[EmpKey], #CurrentEmpKey ) = 1
AND dbo.ExtendFilter( [TA].[AssignatedBy], #CurrentEmpKey ) = 1
AND dbo.ExtendFilter( [TA].[EmpKey], #FilterEmpKey ) = 1
Mind you this is just an example. You'd want to check #pram_value for NULL, etc...

SQL Server conditional where clause

I have the following where clause that begins with the following:
DECLARE #Birthdate = 1
SELECT ...
FROM ...
JOIN ...
WHERE A.organization_id = 1
AND LEFT(A.[first_name], 3) = LEFT(B.[first_name], 3)
AND LEFT(A.[last_name], 3) = LEFT(B.[last_name], 3)
After this I would like to conditionally execute additional clauses.
For example:
if #Birthdate = 1 then add AND A.[birthdate] = B.[birthdate]
otherwise, don't add anything
I've tried the following and none seem to work properly:
Ex 1:
AND (#Birthdate = 1 AND A.[birthdate] = B.[birthdate])
Ex 2:
AND ((#Birthdate = 1 AND A.[birthdate] = B.[birthdate]) OR
(#Birthdate = 0 AND (A.[birthdate] = B.[birthdate] OR
A.[birthdate] <> B.[birthdate])))
Any suggestions as to what I'm doing wrong?
You can use an or to apply your filter, or to just return all rows when #Birthdate = 0
SELECT
...
FROM
...
WHERE
(
-- Apply the filter if applicable
(
#Birthdate = 1
and A.[birthdate] = B.[birthdate]
)
-- Or return everything
or #Birthdate <> 1
)

Is this a syntax error?

IF( #ActiveStatus = 1 )
BEGIN
#PasswordStatus = 3
END
ELSE
SET #PasswordStatus = (SELECT password_status
FROM tbl_user
WHERE login_name = #LoginName_fromApp
AND password=#Pass
)
I am using Microsoft SQL Server Management Studio..
yes
In IF clause you need to set variable so use select or set, do not write directly #PasswordStatus = 3 write set/select #PasswordStatus = 3
try
if( #ActiveStatus = 1 )
begin
--chage of code
set #PasswordStatus = 3 --or select #PasswordStatus = 3
END
else
begin
Set #PasswordStatus = (select password_status from tbl_user where login_name=#LoginName_fromApp and password=#Pass)
end
EDIT
Comment of -# marc_s Use SET #Var = 3 if you're just setting a "scalar" value - use SELECT #Var = ID FROM dbo.Table1 if you're actually selecting from a table (or view)
when you r setting valuer to any variable use Set as followed
if( #ActiveStatus = 1 )
begin
Set #PasswordStatus = 3
END
else
begin
Set #PasswordStatus = (select password_status from tbl_user where
login_name=#LoginName_fromApp and password=#Pass)
end
Select #PasswordStatus
Another one
select
#PasswordStatus = case when #ActiveStatus = 1 then 3 else password_status end
from
tbl_user
where
login_name = #LoginName_fromApp and password=#Pass

comparing three variables

I have three integer variables: firstCount, secondCount, thirdCount. I need to compare it and to output the result. I'm bad at SQL, but C# code is something like this:
if(firstCount == secondCount == thirdCount)
return true;
else
return false;
One way (2008 syntax).
SELECT CAST(CASE
WHEN COUNT(DISTINCT C) = 1 THEN 1
ELSE 0
END AS BIT)
FROM (VALUES (#firstCount),
(#secondCount),
(#thirdCount)) t (C)
declare #first int
, #second int
, #third int
select #first = 0
, #second = 0
, #third = 0
select case when (#first = #second) AND (#second = #third) THEN 1 ELSE 0 END
Following is one way to do it but after reading #meagar's comment, I find that solution to be more elegant. Just waiting for him to turn it into an answer...
DECLARE #firstcount INTEGER
DECLARE #secondcount INTEGER
DECLARE #thirdcount INTEGER
SET #firstcount = 1
SET #secondcount = 2
SET #thirdcount = 3
IF #firstcount <> #secondcount SELECT 0
ELSE IF #secondcount <> #thirdcount SELECT 0
ELSE SELECT 1
You are wanting to say If Firstcount is equal to second count, and secondcount is equal to third count return true.
You can just do
DECLARE #a INT = 2
DECLARE #b INT = 2
DECLARE #c INT = 2
IF (#a = #b AND #a = #c)
BEGIN
Print('true')
END
ELSE
BEGIN
Print('false')
END
Although it makes no difference you dont need to test B = C because A = C is exactly the same thing since all 3 values have to be the same.
Try the code ,
if ( (firstCount = secondCount) and (secondCount = thirdCount) and (firstCount = ThirdCount) )
return true;
else
return false;