IF ELSE CONDITION IN SQL WHERE CLAUSE - sql

MY QUERY IS
DECLARE #AutoApprove BIT
SET #AutoApprove = (
SELECT AutoApprove
FROM dbo.CommentBox_Setting
WHERE UserModuleID = #myModuleID
AND PortalID = #portalID
AND CultureCode = #cultureCode
)
From this i will get whether 1 OR 0 (TRUE OR FALSE) furthermore i have
SELECT * FROM ComentBox_Comment
WHERE UpperModuleID = #UpperModuleID
AND ModuleID = #myModuleID
AND portalID = #portalID
AND cultureCode = #cultureCode
AND //Here i need to check condition
(IF(#AutoApprove=0){ THEN isapprove=1}else {do not check})
Note here isapprove is table filedName
I know ,i can do this with long query i need short and easy way.
Help me out.

Try something like
AND CASE WHEN #AutoApprove=0 THEN isapprove ELSE 1 END = 1
This will check isapprove = 1 if #AutoApprove = 0, or 1=1(ignore) otherwise.
CASE (Transact-SQL)

Related

What is the Purpose of the IsNull in this query?

I have a desktop application that I am converting to web and I am having trouble understanding the purpose of the IsNull parts of the query. The query is for Ms SQL and I know it has a IsNull function but this is not it. So I'm confused as to it's purpose. Below is my query:
UPDATE tb_category
SET
Email = #Email,
CandidateID = #CandidateID,
Code = #Code,
TestDate = #TestDate,
Description = #Description,
PointsEarned = #PointsEarned,
PointsAvailable = #PointsAvailable,
Average25th = #Average25th,
Average75th = #Average75th,
ImportedDate = #ImportedDate,
CreationDate = #CreationDate,
TestNum = #TestNum,
CategoryNum = #CategoryNum
WHERE ((Email = #Original_Email)
AND (CandidateID = #Original_CandidateID)
AND (Code = #Original_Code)
AND (TestDate = #Original_TestDate)
AND ((#IsNull_Description = 1 AND Description IS NULL) OR (Description = #Original_Description))
AND (PointsEarned = #Original_PointsEarned)
AND ((#IsNull_PointsAvailable = 1 AND PointsAvailable IS NULL) OR (PointsAvailable =
#Original_PointsAvailable))
AND ((#IsNull_Average25th = 1 AND Average25th IS NULL) OR (Average25th = #Original_Average25th))
AND ((#IsNull_Average75th = 1 AND Average75th IS NULL) OR (Average75th = #Original_Average75th))
AND ((#IsNull_ImportedDate = 1 AND ImportedDate IS NULL) OR (ImportedDate = #Original_ImportedDate))
AND ((#IsNull_CreationDate = 1 AND CreationDate IS NULL) OR (CreationDate = #Original_CreationDate))
AND (TestNum = #Original_TestNum)
AND (CategoryNum = #Original_CategoryNum));
I tried simplifying the update statement by removing the IsNull sections but that did not work.
In SQL null is not equal (=) to anything—not even to another null, so in your query in case if both values are null (old and new one) you need to take that into account and check values with IS NULL.
I'm seeing this pattern repeated several times in the WHERE clause:
#IsNull_Description = 1 AND Description IS NULL
It means that a variable, #IsNull_SomeColumnName, which is presumably set earlier in the code, has a value of 1, and the column that the variable relates to is currently NULL.
The function IsNull(Param1, Param2) is used to substitute the value of the second parameter for the value of the first parameter if the first parameter IS NULL, and the function returns the value of Param2.
In SQL Server, and quite a few other RDBMSs, the IS NULL syntax is used to check if a value is currently NULL. Here, Description IS NULL will return TRUE if, well, Description is null, and FALSE if it is not.

Filter only get one condition

I have a validation in WHERE clause like:
...
AND (#BDOnly = 0
OR [DT].[Abbreviation] = #IsBDChecked)
AND (#CDOnly = 0
OR [DT].[Abbreviation] = #IsCDChecked)
AND (#PPOOnly = 0
OR [DT].[Abbreviation] = #IsPPOChecked)
AND (#FBOMOnly = 0
OR [DT].[Abbreviation] = #IsFBOMChecked)
AND (#APOnly = 0
OR [DT].[Abbreviation] = #IsAPChecked)
AND (#COOnly = 0
OR [DT].[Abbreviation] = #IsCOChecked)
So each AND clause check if boolean is bit value is 0 or 1, if it's 0 just do any but if it's 1 it do a filter. My problem is
if I'm sending two with value 1, I mean
#BDOnly = 1 and #CDOnly = 1 it only filter one of them instead get two filters I mean:
[DT].[Abbreviation] = #IsBDChecked
and
[DT].[Abbreviation] = #IsCDChecked
What am I doing wrong? Regards
I'm going to take a guess here because there's not enough data. If you want to return a row where Abbreviation matched #IsBDChecked only when #BDOnly is set, and also another row where Abbreviation matches #IsCDChecked when #CDOnly is set, try this:
(#BDOnly = 1
AND [DT].[Abbreviation] = #IsBDChecked)
OR (#CDOnly = 1
AND [DT].[Abbreviation] = #IsCDChecked)
OR (#PPOOnly = 1
AND [DT].[Abbreviation] = #IsPPOChecked)
OR (#FBOMOnly = 1
AND [DT].[Abbreviation] = #IsFBOMChecked)
OR (#APOnly = 1
AND [DT].[Abbreviation] = #IsAPChecked)
OR (#COOnly = 1
AND [DT].[Abbreviation] = #IsCOChecked)
Small representative case:
DECLARE #ADOnly BIT = 0
, #BDOnly BIT = 1
, #CDOnly BIT = 1
, #IsADChecked NVARCHAR(100) = 'A'
, #IsCDChecked NVARCHAR(100) = 'C'
, #IsBDChecked NVARCHAR(100) = 'B'
;WITH myTable AS
(
SELECT * FROM (VALUES ('A'), ('B'), ('C')) X(Abbreviation)
)
SELECT *
FROM myTable
WHERE (#ADOnly = 1 AND Abbreviation = #IsADChecked)
OR (#BDOnly = 1 AND Abbreviation = #IsBDChecked)
OR (#CDOnly = 1 AND Abbreviation = #IsCDChecked)
Yields:
Abbreviation
------------
B
C

Using IF Statement inside a Where Clause in SQL Server

I have two params that are passed in a function which passed down to the SQL string. Variables can be null or has a value (int). If x is not null, use "this" column else use "that" column. I'm using SQL Server.
// Inside a function with two variables passed, x and y
$sql = "
SELECT
[...]
FROM
[...]
WHERE
[...]
AND [...]
-- This is the tricky part
AND
--- if $x is not null, use foo column else use bar column
IF (x, R.column = 2, R.another_column = 3)
[...]
";
Is this possible to select a column based on the value of the variable passed in?
AND
(
($x is not null and R.column = 2) OR
($x is null and R.another_column = 3)
)
Unless I'm misunderstanding, you just need logic, or a case statement would work.
$sql = "
SELECT
[...]
FROM
[...]
WHERE
[...]
AND
[...]
-- This is the tricky part
AND
--- if $x is not null, use foo column else use bar column
-- IF (x, R.column = 2, R.another_column = 3)
(
(X IS NULL AND R.column = 2)
OR
(X IS NOT NULL AND R.another_column = 3)
)
";
AND
--- if $x is not null, use foo column else use bar column
case
when x is NULL then R.another_column = 3
else R.column = 2
end
--in SQL Server...
DECLARE #x INT = 3;
SELECT *
FROM sys.schemas
WHERE (#x IS NULL AND schema_id = 2)
OR (#x IS NOT NULL and schema_id = 3)
--optional depending on how much you execute this query, it may help
OPTION(RECOMPILE)

If Var is certain Value omit the WHERE

Is it possible to omit the WHERE if a variable is a certain value? The following doesn't work and I am struggling to find an answer;
DECLARE #rMonth int, #rYear int, #sID int
SET #rMonth = 0;
SET #rYear = 0;
SET #sID= 0;
SELECT
TCS.bStatus AS jStatus, TCS.ID, TCS.sID, TCS.insDate, TCS.statusLabel, TCS.cID
FROM
TCS
CASE WHEN #rMonth > 0 THEN
WHERE month(insDate) = #rMonth AND year(insDate) = #rYear
END
This is common scenario to include a clause conditionally
check this out:
WHERE
(#rMonth = 0 OR MONTH(insDate) = #rMonth)
AND (#rYear = 0 OR YEAR(insDate) = #rYear)
AND (#sID = 0 OR sID = #sID)
In above query and for each clause, right hand side of "OR" is applied only if left hand side is false. Otherwise whole clause is considered as true and does not filter any row.
Hopefully,by using above trick any complex clause could be written in right side of "OR" rather than a simple equality comparision.
WHERE
(#rMonth <= 0)
OR
(month(insDate) = #rMonth AND year(insDate) = #rYear)
Another two options to achieve the same result:
one - using CASE statement like you wanted initially:
WHERE MONTH(insDate) = CASE WHEN #rMonth > 0 THEN #rMonth ELSE MONTH(insDate) END
AND YEAR(insDate) = CASE WHEN #rYear > 0 THEN #rYear ELSE YEAR(insDate) END
AND sID = CASE WHEN #sID > 0 THEN #sID ELSE sID END
and another - using ISNULL and NULLIF functions:
WHERE MONTH(insDate) = ISNULL(NULLIF(#rMonth, 0), MONTH(insDate))
AND YEAR(insDate) = ISNULL(NULLIF(#rYear, 0), YEAR(insDate))
AND sID = ISNULL(NULLIF(#sID, 0), sID)

Conditional operator in Transact-sql

Is there a way to do this shorter, for instance using some sort of conditional operator in Transact-sql?
IF #ParentBinaryAssetStructureId = -1
BEGIN
SET #ParentBinaryAssetStructureId = NULL
END
UPDATE BinaryAssets.BinaryAssetStructures
SET ParentBinaryAssetStructureId = #ParentBinaryAssetStructureId
WHERE BinaryAssetStructureId = #OriginalBinaryAssetStructureId
USE NULLIF()
UPDATE BinaryAssets.BinaryAssetStructures
SET ParentBinaryAssetStructureId = NULLIF(#ParentBinaryAssetStructureId,-1)
WHERE BinaryAssetStructureId = #OriginalBinaryAssetStructureId
The ternary (conditional) operator in c like languages:
x = doSomething ? 5 : 7
would be written like this in SQL:
SELECT #x = CASE WHEN #doSomething = 1 THEN 5 ELSE 0 END
There can be multiple cases (when clauses):
SELECT #x = CASE WHEN #doSomething = 1 THEN 5 WHEN #somethingElse = 1 THEN 20 ELSE 0 END
UPDATE BinaryAssets.BinaryAssetStructures
SET ParentBinaryAssetStructureId =
CASE ParentBinaryAssetStructureId
WHEN -1 THEN NULL
ELSE ParentBinaryAssetStructureId
END
WHERE BinaryAssetStructureId = #OriginalBinaryAssetStructureId
Give that a whirl