Optional where clause depending on parameter value - sql

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

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

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
)

Nested CASE WHEN statement

I have one CASE WHEN condition (CompanyGUID and LineGUID) and I need 4 different calculations with 4 different columns.
The calculation works fine, but I just wonder is any way to make it more convenient? like for example maybe using COALESCE trick in this case?
CASE WHEN dbo.tblCompanyLocations.CompanyGUID = '29634AF7-D0A2-473D-9574-405C23E10F02'
AND dbo.tblQuotes.LineGUID = '1CB72920-B3FC-4822-8030-37B50A2810EB'
THEN isnull(ddaWC.archexMod,1)
END as ExperienceMod,
CASE WHEN dbo.tblCompanyLocations.CompanyGUID = '29634AF7-D0A2-473D-9574-405C23E10F02'
AND dbo.tblQuotes.LineGUID = '1CB72920-B3FC-4822-8030-37B50A2810EB'
THEN case when convert(int,ddawc.premModTtl) <= 0 then 1
when convert(int,ddawc.premModTtl) >= 0
then (1 + ddaWC.premschmod / ddawc.premModTtl) end
END as ScheduleMod,
CASE WHEN dbo.tblCompanyLocations.CompanyGUID = '29634AF7-D0A2-473D-9574-405C23E10F02'
AND dbo.tblQuotes.LineGUID = '1CB72920-B3FC-4822-8030-37B50A2810EB'
THEN isnull(ddaWC.TMpercent,1) END as TerritoryMod,
CASE WHEN dbo.tblCompanyLocations.CompanyGUID = '29634AF7-D0A2-473D-9574-405C23E10F02'
AND dbo.tblQuotes.LineGUID = '1CB72920-B3FC-4822-8030-37B50A2810EB'
THEN case when convert(int,ddaWC.SchedPercent) = 0 or
ddaWC.SchedPercent is not null
then (isnull(ddaWC.archexMod,1)
* (convert(decimal(5,2),isnull(ddaWC.SchedPercent,1))))
* isnull(ddaWC.TMpercent,1)
when ddaWC.SchedPercent is null
then 1 END
END as EffectiveMod
Something like this? The OUTER APPLY will perform a row-based select which return NULLs in case of your condition not being fullfilled. Otherwise it will return the same values you've specified. This will only work, if you really need the same logic for all columns.
SELECT otherColumn
,ConditionalColumns.*
FROM YourTable
OUTER APPLY
(
SELECT isnull(ddaWC.archexMod,1) as ExperienceMod,
case when convert(int,ddawc.premModTtl) <= 0 then 1
when convert(int,ddawc.premModTtl) >= 0
then (1 + ddaWC.premschmod / ddawc.premModTtl) end as ScheduleMod,
isnull(ddaWC.TMpercent,1) as TerritoryMod,
case when convert(int,ddaWC.SchedPercent) = 0 or ddaWC.SchedPercent is not null
then (isnull(ddaWC.archexMod,1)
* (convert(decimal(5,2),isnull(ddaWC.SchedPercent,1))))
* isnull(ddaWC.TMpercent,1)
when ddaWC.SchedPercent is null
then 1 END as EffectiveMod
WHERE dbo.tblCompanyLocations.CompanyGUID = '29634AF7-D0A2-473D-9574-405C23E10F02'
AND dbo.tblQuotes.LineGUID = '1CB72920-B3FC-4822-8030-37B50A2810EB'
) AS ConditionalColumns
Like this:
somewhere before code:
Declare #compGuid char(37) = '29634AF7-D0A2-473D-9574-405C23E10F02'
Declare #lineGuid char(37) = '1CB72920-B3FC-4822-8030-37B50A2810EB'
and modify From Clause in SQL statement to define aliases
cl for tblCompanyLocations, and
q for tblQuotes
then the case in the Select clause of the SQL code could be reduced to:
case when cl.CompanyGUID = #compGuid
and q.LineGUID = #lineGuid
then isnull(ddaWC.archexMod,1) end ExperienceMod,
case when cl.CompanyGUID = #compGuid
and q.LineGUID = #lineGuid
then case when cast(ddawc.premModTtl as int) > 0
then (1 + ddaWC.premschmod / ddawc.premModTtl)
else 1 end end ScheduleMod,
case when cl.CompanyGUID = #compGuid
and q.LineGUID = #lineGuid
then isnull(ddaWC.TMpercent,1) end TerritoryMod,
case when cl.CompanyGUID = #compGuid
and q.LineGUID = #lineGuid
then case when cast(ddaWC.SchedPercent as int) = 0
then isnull(ddaWC.archexMod,1)
* cast(ddaWC.SchedPercent as decimal(5,2)))
* isnull(ddaWC.TMpercent,1)
when ddaWC.SchedPercent is null
then 1 end end EffectiveMod
which is a bit more readable... (check the logic though)

If Else not working in TSQL

If is never working. Always falling in else condition. I have debugged and checked #nextapprover is not null.
IF (#nextApprover != NULL)
BEGIN
UPDATE CallWatching
SET EmployeeNo = #employeeNo
WHERE #SRFID = MasterCode;
INSERT INTO CallForwarding (
MasterCode
,EmployeeNo
,ApproverNo
,IsForwarded
,ForwardBy
)
VALUES (
#SRFID
,#EmployeeNo
,#nextApprover
,0
,#EmployeeNo
)
END
ELSE
BEGIN
UPDATE CallWatching
SET STATUS = 1
WHERE #SRFID = MasterCode;
END
Use IS NOT NULL
i.e. Change: if(#nextApprover!=null)
to IF(#nextApprover IS NOT NULL)
Additionally you should <> instead of != as it is ANSI compliant