SQL Boolean Vars in Where stament - sql

I am making an rdl report and I have three check-boxes that if checked need to alter my WHERE statement. If none are checked the result should only match by date range. If one or more are checked it needs to return the fields that match the variables corresponding string.
WHERE
(EffectiveDate BETWEEN #StartDate AND #EndDate)
AND (((#IncludeSEWPrefix = 1 AND PrefixId = 'SEW') OR #IncludeSEWPrefix = 0)
AND ((#IncludePAWPrefix = 1 AND PrefixId = 'PAW') OR #IncludePAWPrefix = 0)
AND ((#IncludeRPLPrefix = 1 AND PrefixId = 'RPL') OR #IncludeRPLPrefix = 0))
My code so far works when none are checked and when one is checked, but returns nothing when more than one check-box has been checked. So to try and fix this I altered the code to this
WHERE
(EffectiveDate BETWEEN #StartDate AND #EndDate)
AND ((((#IncludeSEWPrefix = 1 AND PrefixId = 'SEW') OR #IncludeSEWPrefix = 0)
OR ((#IncludePAWPrefix = 1 AND PrefixId = 'PAW') OR #IncludePAWPrefix = 0)
OR ((#IncludeRPLPrefix = 1 AND PrefixId = 'RPL') OR #IncludeRPLPrefix = 0)))
Which resulted in all rows being returned no matter what was selected. Can someone tell me where I am going wrong?

I believe this is the correct rearrangement. Trickier problem than it first appears. The issue was seperating lines like ((#IncludeSEWPrefix = 1 AND PrefixId = 'SEW') OR #IncludeSEWPrefix = 0) with AND meant that if two includes were true, a row would need to have both PrefixId's, which can't happen. And if you separated them with OR, then having just one include false, means that every row will pass. So instead, check that a row has the prefix of any that are included, otherwise all includes have to be off.
WHERE EffectiveDate BETWEEN #StartDate AND #EndDate
AND
(
(#IncludeSEWPrefix = 1 AND PrefixId = 'SEW') OR
(#IncludePAWPrefix = 1 AND PrefixId = 'PAW') OR
(#IncludeRPLPrefix = 1 AND PrefixId = 'RPL') OR
(#IncludeSEWPrefix = 0 AND #IncludePAWPrefix = 0 AND #IncludeRPLPrefix = 0)
)

Try this
WHERE
(EffectiveDate BETWEEN #StartDate AND #EndDate)
AND
(
(#IncludeSEWPrefix = 1 AND PrefixId = 'SEW' OR #IncludeSEWPrefix = 0) AND
(#IncludePAWPrefix = 1 AND PrefixId = 'PAW' OR #IncludePAWPrefix = 0) AND
(#IncludeRPLPrefix = 1 AND PrefixId = 'RPL' OR #IncludeRPLPrefix = 0)
)

You have more parenthesis than needed, it does not hurt but just be aware.
Maybe this can help:
WHERE (EffectiveDate BETWEEN #StartDate AND #EndDate)
AND ( ((#IncludeSEWPrefix = 1 AND PrefixId = 'SEW') OR (#IncludeSEWPrefix = 0 AND #PrefixId <> 'SEW'))
OR ((#IncludePAWPrefix = 1 AND PrefixId = 'PAW') OR (#IncludePAWPrefix = 0 AND #PrefixId <> 'PAW'))
OR ((#IncludeRPLPrefix = 1 AND PrefixId = 'RPL') OR (#IncludeRPLPrefix = 0 AND #PrefixId <> 'RPL'))
)

Related

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

Catching last datetime after update wont result

I have the following code:
UPDATE sm
SET sm_fecha_venc = (SELECT MIN(nd_fecha_venc) FROM [db_facturacion].[dbo].[tb_notas_debito]
WHERE sm_codigo = nd_num_servicio
-- AND nd_referencia = sm_cod_producto
AND nd_num_factura = sm_cod_factura
AND nd_estado = 'G')
,sm_fecha_ult_pago = (SELECT MAX(nd_fecha_pago) FROM [db_facturacion].[dbo].[tb_notas_debito]
WHERE sm_codigo = nd_num_servicio
-- AND nd_referencia = sm_cod_producto
AND nd_num_factura = sm_cod_factura
AND nd_estado = 'C')
,sm_fecha = GETDATE()
,sm_cod_factura_ren = #i_num_factura
OUTPUT DELETED.sm_fecha_venc AS FECHA_VENC_OLD,
DELETED.sm_fecha_ult_pago AS FECHA_ULT_PAGO_OLD,
DELETED.sm_fecha AS FECHA_OLD,
DELETED.sm_cod_factura_ren AS COD_FACTURA_REN_OLD
INTO #TABLATABLA --
FROM [db_facturacion].[dbo].[tb_servicios] sm --WITH(NOLOCK)
INNER JOIN #servicios AS T ON sm_codigo = num_servicio
WHERE sm_tipo_bien_protegido = 1
AND [sm_estado] = 1
--AND sm.sm_cod_forma_contrato = 1
AND sm.sm_tipo_inventario = tipo_inventario
/*===========================
INSERTED DELETED
=============================*/
UPDATE db_facturacion.[dbo].[tb_log_cambio_servicio]
SET cs_fecha_venc_old = FECHA_VENC_OLD
,cs_fecha_ult_pago_old = FECHA_ULT_PAGO_OLD
,cs_fecha_old = FECHA_OLD
,cs_cod_factura_ren_old = COD_FACTURA_REN_OLD
FROM #TABLATABLA
WHERE cs_codigo = #ID_ULTIMO_ING (LAST ##IDENTITY)
Im trying to save the last dates into a log table, just in case I have to return those dates back.
The code works good, just that it's catching the actual date and inserted in the log table.
What am I missing?

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)

Understanding case expression in the "Where" clause

I've got this code here and you can see from my Pseudocode what I'm trying to accomplish
select *
from dbo.BenefitsForms
inner join Dependents on BenefitsForms.UserId = Dependents.BenefitsForm_UserId
inner join CoverageLevels on BenefitsForms.MedicalId = CoverageLevels.Id
where (BenefitsForms.MedicalId > 0 AND BenefitsForms.MedicalId < 13)
AND Dependents.IsSpouse = CASE when CoverageLevels.[Level] = 2 then 1
when CoverageLevels.[Level] = 3 then 0 end
when CoverageLevels.[Level] = 4 then [any, it doesnt matter] <--- my desire but it doesn't work.
What can I do to get the effect I desire in the brackets? If Coverage Level = 4 then I don't care what Dependents.IsSpouse is, I don't even need to sort by it anymore.
Assuming that isSpouse can only be 0 or 1... if CoverageLevels.Level is 4, then compare isSpouse to itself, which will always result in true:
AND Dependents.IsSpouse = CASE
when CoverageLevels.[Level] = 2 then 1
when CoverageLevels.[Level] = 3 then 0
when CoverageLevels.[Level] = 4 then Dependents.IsSpouse
END
Alternately, this can also be expressed without the CASE:
WHERE
BenefitsForms.MedicalId > 0
AND BenefitsForms.MedicalId < 13
AND (
(Dependents.IsSpouse = 1 AND CoverageLevels.[Level] = 2)
OR (Dependents.IsSpouse = 0 AND CoverageLevels.[Level] = 3)
OR CoverageLevels.[Level] = 4
)

SELECT FROM depending on a parameter in SQL

I want to obtain from a parameter, #Display the value 0, 1 or 2. When #Display = 0, I want to display all the items for which ec.IsEquipmentRelated is true. When #Display = 0, I want to display all the items for which ec.IsEquipmentRelated is false and when #Display = 2, I want to display all the items for which ec.IsEquipmentRelated is true OR false. How can I implement this in the FROM section?
ALTER PROCEDURE [dbo].[Downtime_GetNewCause_EquimentLocation]
#DisplayInactive bit = 0,
#SortOrder INT = 0,
#Diplay INT = 0
AS
-- Main Data source
SELECT ic.IncidentCauseID
, 'EquimentRelated' = COALESCE(ec.IsEquipmentRelated, 0)
, ic.NewIncidentCauseID
, ic.DisplayName
, ic.IsLegacy
, el.EquipmentLocationID
, el.ShopID
, ec.EquipmentClassID
, ec.EquipmentAbbr
, el.ClassSequenceNumber
, el.EquipmentComponent
, el.CompSequenceNumber
, ic.IsActive
FROM Downtime_IncidentCauses ic
LEFT JOIN Downtime_EquipmentLocations el ON ic.EquipmentLocationID = el.EquipmentLocationID
LEFT JOIN Downtime_EquipmentClasses ec ON el.EquipmentClassID = ec.EquipmentClassID AND
CASE WHEN #Diplay = 0 THEN ...
CASE WHEN #Diplay = 1 THEN ...
CASE WHEN #Diplay = 2 THEN ...
This should work:
INNER JOIN Downtime_EquipmentClasses ec
ON (el.EquipmentClassID = ec.EquipmentClassID)
AND ( (#Display = 0 AND ec.IsEquipmentRelated = 1)
OR (#Display = 1 AND ec.IsEquipmentRelated = 0)
OR (#Display = 2) )
Do it in a WHERE clause:
WHERE (#Display = 0 AND ec.IsEquipmentRelated = 'True')
OR (#Display = 1 AND ec.IsEquipmentRelated = 'False')
OR #Display = 2