How to remove condition check in the where clause statement? - sql

I would like to know how to use if/else or case statement in the below query or anything that could achieve the purpose.
The idea is that, whenever a keyword is NULL or blank, I don't want to include the pv.AdminPost = 1 and pv.IsStaff = 1 condition in the Where statement.
Is there any way to do it? Thank you.
;WITH cte
AS (SELECT fv.Id, fv.[Description]
FROM FeedView fv
WHERE (fv.Id = #PostId OR fv.[Description] LIKE '%' + #Keyword + '%' OR #Keyword IS NULL ) AND fv.ForUserId = #UserId
UNION
SELECT pv.Id, pv.[Description]
FROM PublicView pv
WHERE #InculdePublicPosts = 1 -- This acts as an off switch to decide whether to include public post or not.
OR pv.AdminPost = 1 OR pv.IsStaff = 1 -- how to remove this condition when Keyword is NULL or empty
AND (pv.Id = #PostId OR pv.[Description] LIKE '%' + #Keyword + '%' OR #keyword IS NULL )
)
SELECT cte.Id, cte.[Description]
FROM .....

You must use proper paranthesis and OR condition as follows:
WHERE #InculdePublicPosts = 1
AND ((#keyword IS NULL OR #keyword = '') OR pv.AdminPost = 1 OR pv.IsStaff = 1)
AND (pv.Id = #PostId OR pv.[Description] LIKE '%' + #Keyword + '%' OR #keyword IS NULL )

You can do it this way
AND (ISNULL(keyword, '') = '' OR (pv.AdminPost = 1 OR pv.IsStaff = 1))
Explain:
Using ISNULL() function to get the empty value in case that keyword is null.
If keyword is NULL or blank, then the remaining condition will not run thanks to OR condition. Example:
false or true --> true
true or false --> true
true or true --> true
false or false --> false

Related

SQL Server - CASE on where clause

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

MSSQL Case denoted by an integer returns a string

I have an issue with my SELECT statement in SSRS.
I want to use an integer to return strings values.
I tried it with this SELECT clause:
SELECT CASE #param = '1' THEN value like '__%' ELSE value like ' '
But it doesn't work, so I tried to use this one instead:
WHERE
((#param = '1' AND value like '__%') OR (#param = '0' AND value = '%'))
The expected result is: When the case is "1" SELECT should return only values which are not ' '
When the case is "0" SELECT should return all values = ' ' + '__%'
Thank you for your help
Your case condition is wrong formatted. You missed WHEN and END .It should be like that:
SELECT CASE WHEN #param = '1' THEN value like '__%' ELSE value like ' ' END
EDIT : As much as I understand you want to see Value if the #param='1' and if not the result will be '__%'. If yes this following CASE usage should be correct:
SELECT CASE WHEN #param = '1' THEN value ELSE value= '__%' END
I fix it my self condition is
((#column = '1' AND column like '__%') OR (#column = '0'AND column like '_%'))
WHERE
((#param = '1' AND value != '') OR (#param = '0'))
just try this

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...

Optional where clause depending on parameter value

I want the where statement for this query to be optional depending on what the value of parameter #RetrieveAll is. If #RetrieveAll is false/null the where statement is used, if it is true it should be ignored.
#IncludeErrors bit = 1,
#IncludeAccess bit = 1,
#IncludeLogins bit = 1,
#RetrieveAll bit = NULL
SELECT
//...
FROM
(
) AS a
WHERE
a.RowNumber BETWEEN #ItemCountStart AND #ItemCountEnd
Is there way to do this?
SELECT
//...
FROM
(
) AS a
WHERE
(a.RowNumber BETWEEN #ItemCountStart AND #ItemCountEnd AND #RetrieveAll IS NULL)
OR
#RetrieveAll IS NOT NULL
You should try this,
Select * from Tablename a
Where
1 = case when isnull(#RetriveAll,0) == 0 then
case when a.RowNumber BETWEEN #ItemCountStart AND #ItemCountEnd then 1 else 0 end
else 1 end

constraint formulation in inner join

I've the following problem. Take a look at this part of query
inner join tObjClassifier azoc WITH (NOLOCK index=XAK1tDepClassifier)
on azoc.ObjType = 8
and azoc.ParentID = #ObjClassifierID
and azoc.Brief = azfo.Brief
and case
when PATINDEX( ('%' + ltrim(rtrim(azn.Brief)) + '%' ) , azoc.Param) is null then azn.NodeType = 2
else PATINDEX( ('%' + ltrim(rtrim(azn.Brief)) + '%' ) , azoc.Param)>0
end
here , I'm interested in this part
and case
when PATINDEX( ('%' + ltrim(rtrim(azn.Brief)) + '%' ) , azoc.Param) is null then azn.NodeType = 2
else PATINDEX( ('%' + ltrim(rtrim(azn.Brief)) + '%' ) , azoc.Param)>0
end
How can I do this part without getting errors. Briefly, If condition PATINDEX( ('%' + ltrim(rtrim(azn.Brief)) + '%' ) , azoc.Param)>0
not satisfied, disregard this condition and use this azn.NodeType = 2 condition. Thanks.
we can rearrange above condition as this also:
and case
when ltrim(rtrim(azn.Brief)) = azoc.Param is null then azn.NodeType = 2
else ltrim(rtrim(azn.Brief)) = azoc.Param)
end
PATINDEX returns the starting position of the first occurrence of a pattern in a specified expression, or zeros if the pattern is not found. So try use OR condition:
...
and azoc.Brief = azfo.Brief
and
(
(PATINDEX( ('%' + ltrim(rtrim(azn.Brief)) + '%' ) , azoc.Param)>0)
OR
(azn.NodeType = 2)
)