SQL Server Case statement in WHERE Clause - sql-server

I tried to google for CaseStatement in WHERE clause. But i didn't find similar to my scenario.
Below is my SQL Statement with CASE Statement in WHERE clause. If PartName = B, then i should apply (RecoveraleFlag = 1) condition along with other conditions. Else This condition should not apply but all other conditions should remain.
FROM Rec.Communications A
INNER JOIN REC.CommunicationTypes B ON A.CommunicationTypeKey = B.CommunicationTypeKey
INNER JOIN occ.Cases c ON a.CaseId = c.CaseId
INNER JOIN occ.Claims cl on a.CaseId = cl.CaseId
INNER JOIN ops.Concepts d ON c.ConceptKey = d.ConceptKey
INNER JOIN OPS.Regions f ON d.MODSRegionKey = f.MODSRegionKey
INNER JOIN COM.RepriceRequestOccurrences e ON a.CommunicationId = e.CommunicationId
INNER JOIN occ.Providers prv ON c.MODSProviderKey = prv.MODSProviderKey
WHERE
**(
CASE WHEN f.PartName = 'B' and e.RecoverableFlag = 1 then 1
ELSE 0
END
) = 1**
AND
b.CommunicationTypeCode = 'RREQ'
AND f.Region = #Region
AND a.CurrentFlag = 1
Here Case Statement in where clause is working fine if Partname = B. For Partname A, this will be 0=1 – always false. Because of this it is not returning any data.
Can anyone gives any alternatives.

As a case statement, you would write this as:
CASE WHEN f.PartName = 'B' and e.RecoverableFlag = 1 then 1
WHEN f.ParName = 'A' then 1
ELSE 0 END ) = 1
Is this the logic you want?
Many would think that the case statement is irrelevant here, and instead use:
WHERE ((f.PartName = 'B' and e.RecoverableFlag = 1) or (f.partName <> 'B')) . . .

WHERE
(
f.PartName <> 'B'
OR e.RecoverableFlag = 1
)
AND b.CommunicationTypeCode = 'RREQ'
AND f.Region = #Region
AND a.CurrentFlag = 1
You might find reading on De Morgan's Laws interesting.

I don't believe you need a case statement at all.. The following should work...
WHERE f.PartName = 'B'
And e.RecoverableFlag = 1
AND b.CommunicationTypeCode = 'RREQ'
AND f.Region = #Region
AND a.CurrentFlag = 1
But if you want to use a case statement in a where clause, try to put it on the "other" side of the comparison operator from the column name so the query can process it without doing a table scan...
as an e.g.,
Where f.Partname =
Case b.CommunicationTypeCode
When 'RREQ' Then 'B'
When 'NOTREQ' Then 'C'
When 'OPT' Then 'D'
Else 'F' End

Related

How to create table from a query with a case clause column in DB2?

Hello I am trying to create a table from a query like this: (sort of)
create table afiexdb.afiext as(
select a.afiaux, a.aficod, a.aficta, a.afidep, b.mb_nom_reg as AFIDEPDSC, a.afimun, d.mb_nom_ciu as AFIMUNDSC, a.afidirchk, a.afifching, a.afidptnac, c.mb_nom_reg as DPTNACDSC, a.afimunnac, e.mb_nom_ciu as MUNNACDSC,
cast(CASE WHEN a.afiestciv = 'S' THEN 'SOLTERO'
                 WHEN a.afiestciv = 'C' THEN 'CASADO'
                 WHEN a.afiestciv = 'D' THEN 'DIVORCIADO'
                 WHEN a.afiestciv = 'V' THEN 'VIUDO'
                 WHEN a.afiestciv = 'U' THEN 'UNION LIBRE'
                 END as char(11)) as AFIESTCIV,
a.afifchmue, a.afifchnac, a.afifchprm, a.afifchret, a.afihom, a.afinro, a.afiprof, a.afiserie, a.afisexo, a.afiults, rtrim(a.cli1ernomb)||' '||rtrim(a.cli2donomb)||' '||rtrim(a.cli1erapel)||' '|| rtrim(a.cli2doapel) as AFINOMBRE,
rtrim(a.clidirec1)||' '||rtrim(a.clidirec2)||' '||rtrim(a.clidirec3) as AFIDIR, a.cliidentid, f.afitel1, f.afitel2, f.afitel3,
a.estcod, g.estdsc, h.gracod, h.gradsc, a.grucod, i.grudsc, a.unicod, j.unidsc,
m.pplcod as PAGCOD, m.ppldsc as PAGDSC, afiedad(a.aficod, a.afihom, cast ('20170405' as char(8))) as EDADAFI,
ifnull(n.pricot,0) as PRICOT, ifnull(n.ultcot,0) as ULTCOT, n.totcot as TOTCOT, n.anioscot, cast(null as decimal) as RESLAB
from afiliadbf.afiliado a
left join lisamb30db.regdep b on b.mb_region = a.afidep
left join lisamb30db.regdep c on c.mb_region = a.afidptnac
left join lisamb30db.region d on a.afidep = d.mb_region and a.afimun = d.mb_ciudad
left join lisamb30db.region e on a.afidptnac = e.mb_region and a.afimunnac = e.mb_ciudad
left join afiliadbf.afiadinf f on a.aficod = f.aficod and a.afihom = f.afihom
left join afiliadbf.estado g on a.estcod = g.estcod
left join afiliadbf.grado h on a.gracod = h.gracod
left join afiliadbf.grupo i on a.grucod = i.grucod
left join afiliadbf.unidad j on a.unicod = j.unicod
left join prsipmdb2.pagunida l on a.unicod = l.pagunidad
left join afiliadbf.platip m on l.pagcod = m.pplcod
left join (select a.aficod, a.afihom, MIN(rtrim(a.cotanio)||'-'||case when a.cotmes<10 then '0'||a.cotmes else rtrim(a.cotmes)end cotaniomes) as pricot,
MAX(rtrim(a.cotanio)||'-'||case when a.cotmes<10 then '0'||a.cotmes else rtrim(a.cotmes) end cotaniomes) as ultcot, sum(a.cotmon) as totcot,
cast(count(a.cotanio)/12 as char(2))||' Años '||cast(count(a.cotanio)-(count(a.cotanio)/12)*12 as char(2))||' meses' as anioscot
from afiliadbf.cotiza a
group by a.aficod, a.afihom) n on n.aficod = a.aficod and n.afihom = a.afihom
) with no data
I get invalid symbol when I include the case clause column. I know DB2 is strong typed so that is why I casted each result value as varchar I also tried to cast the entire case clause [cast(case()end as char(10)], and definitely can not have a 'cast as' somewhere if not some error will pop up for sure.
Any advice on how to create this column based on the case clause column?
try to modify your case like this (you have forget 'ELSE' into your case) :
CASE
WHEN a.afiestciv = 'S' THEN 'SOLTERO'
WHEN a.afiestciv = 'C' THEN 'CASADO'
WHEN a.afiestciv = 'D' THEN 'DIVORCIADO'
WHEN a.afiestciv = 'V' THEN 'VIUDO'
WHEN a.afiestciv = 'U' THEN 'UNION LIBRE'
ELSE cast(null as char(11))
END as AFIESTCIV

What causing errors with this stored procedure?

I have a stored procedure to process monthly jobs. The stored procedure will loop through all the available jobs and do some calculation before it's inserted into a table. It was fine for most jobs but for some jobs, there will be an error
Subquery returned more than 1 value. This is not permitted when the
subquery follows =, !=, <, <= , >, >= or when the subquery is used as
an expression.
Below is the section where it says the error occurred:
IF EXISTS( SELECT *
FROM aastocks aastk
WHERE aastk.estno = #lcEstno
and 0 in (aastk.cartonratio1,
aastk.cartonratio2,
aastk.cartonratio3,
aastk.cartonratio4,
aastk.cartonratio5)
) EXECUTE ru_est_stocksum #lcEstNo
#lcEstNo was defined in the previous code.
SET #lcEstno = (SELECT MAX(estno) FROM dbo.v_est_joblist WHERE ljob = #tcLjob)
MAX() should return only 1 value and I don't understand why the multi value error.
Well, as it turns out, the line number of the error is not the same as the line number in the Stored Procedure. So the problem actually resides in the following code(After I comment out the below section and there is no error). But I am not able to find out which subquery is returning more than 1 value. Any idea ?
INSERT INTO #JCDTotals
SELECT #tcLjob, coalesce(cast( ap.deptno as char(4)),'????') as deptno,
CASE WHEN coalesce(v_depuse_qty.DepUse, 1) = 1 THEN
CASE WHEN #tcCostBase = 'D' THEN CASE WHEN ap.procgroup = 'I' THEN aaprocqt.dmcstmat1 + aaprocqt.dmcstmat2 + aaprocqt.dmcstmat3 END
WHEN #tcCostBase = 'A' THEN CASE WHEN ap.procgroup = 'I' THEN aaprocqt.costmats1 + aaprocqt.costmats2 + aaprocqt.costmats3 END
ELSE ' 0 '
END
ELSE 0 END AS ecostmats,
CASE WHEN coalesce(v_depuse_qty.DepUse, 1) = 1 THEN CASE WHEN #tcCostBase = 'D' THEN (1 / (1 + (ap.burden/100))) ELSE 1 END
* aaprocqt.costlab
ELSE 0
END AS ecostlab,
CASE WHEN coalesce(v_depuse_qty.DepUse, 1) = 1 THEN aaprocqt.proctime
ELSE 0
END AS eprochours,
0.0 AS bcostmats,
0.0 AS bcostlab,
0 AS bprochours,
0.0 AS acostmats,
0.0 AS acostlab,
0 AS aprochours,
0.0 AS chgcost,
0 AS dirlab,
0.0 AS aacost,
0.0 AS pecost,
0.0 AS otcost,
0 AS sell
FROM (
SELECT aaproces.idnumber,
aaproces.estno,
aaproces.procgroup,
aaproces.partno,
aaproces.[lineno],
aaproces.counter,
ssproces.burden,
case WHEN aaproces.procgroup = 'I' then ssinvent.deptno
else ssproces.deptno end as deptno,
case WHEN aaproces.procgroup = 'I' then ssinvent.matno
else STR(ssproces.procno,6) end as procno,
case WHEN aaproces.procgroup = 'I' then ssinvent.material
else ssproces.process end as process
FROM dbo.aaproces
LEFT JOIN dbo.SSINVENT ON ssinvent.matno = aaproces.matno
AND ssinvent.invtype IN ('G', 'I', 'F', 'S')
LEFT JOIN dbo.SSPROCES ON ssproces.procno = aaproces.procno
WHERE ((aaproces.procgroup = 'I' and ssinvent.deptno is not null)
OR (aaproces.procgroup <> 'I' and ssproces.deptno is not null))
AND ((aaproces.procgroup = 'I' and ssinvent.matno is not null)
OR (aaproces.procgroup <> 'I' and ssproces.procno is not null))
) ap
INNER join dbo.v_est_joblist
on v_est_joblist.estno = ap.estno
LEFT OUTER JOIN dbo.aaprocqt
on aaprocqt.estno = ap.estno
and ap.[lineno] = aaprocqt.[lineno]and aaprocqt.procgroup = ap.procgroup
and ap.partno = aaprocqt.partno and ap.counter = aaprocqt.counter and aaprocqt.qty = v_est_joblist.alt
LEFT OUTER JOIN dbo.v_depuse_qty
ON v_est_joblist.estno = v_depuse_qty.estno
AND v_depuse_qty.deptno = ap.deptno
AND V_DEPUSE_QTY.LJOB = V_EST_JOBLIST.LJOB
AND V_DEPUSE_QTY.ALT = V_EST_JOBLIST.ALT
WHERE v_est_joblist.ljob = #tcLjob
-- AND ssdept.divno like #lcDivNo
--------------------------------------------------------------------------- PROCESS MATERIAL1,MATERIAL2,MATERIAL3 (ESTIMATED)
UNION ALL
SELECT #tcLjob, coalesce(ssinvent.deptno,'????') as deptno,
CASE WHEN coalesce((SELECT v_depuse_qty.DepUse FROM dbo.v_depuse_qty WHERE v_est_joblist.estno = v_depuse_qty.estno
AND ssinvent.deptno = v_depuse_qty.deptno
AND V_DEPUSE_QTY.LJOB = V_EST_JOBLIST.LJOB
AND V_DEPUSE_QTY.ALT = V_EST_JOBLIST.ALT), 1) = 1 THEN CASE WHEN sq.CopyNum = 1 THEN CASE WHEN #tcCostBase = 'D' THEN aaprocqt.dmcstmat1 ELSE aaprocqt.costmats1 END
WHEN sq.CopyNum = 2 THEN CASE WHEN #tcCostBase = 'D' THEN aaprocqt.dmcstmat2 ELSE aaprocqt.costmats2 END
WHEN sq.CopyNum = 3 THEN CASE WHEN #tcCostBase = 'D' THEN aaprocqt.dmcstmat3 ELSE aaprocqt.costmats3 END
END
ELSE 0
END AS ecostmats,
0 AS ecostlab,
0 AS eprochours,
0 AS bcostmats,
0 AS bcostlab,
0 AS bprochours,
0.0 AS acostmats,
0.0 AS acostlab,
0 AS aprochours,
0.0 AS chgcost,
0 AS dirlab,
0.0 AS aacost,
0.0 AS pecost,
0.0 AS otcost,
0 AS sell
FROM dbo.aaproces JOIN dbo.v_est_joblist on v_est_joblist.estno = aaproces.estno
CROSS JOIN #NumCopies sq
LEFT JOIN dbo.ssproces on aaproces.procno = ssproces.procno
LEFT JOIN dbo.ssinvent on ssinvent.matno = ( case when sq.CopyNum = 1 then CASE WHEN aaproces.manmatno = '' THEN ssproces.matno1 ELSE aaproces.manmatno END
when sq.CopyNum = 2 then CASE WHEN aaproces.manmatno2 = '' THEN ssproces.matno2 ELSE aaproces.manmatno2 END
when sq.CopyNum = 3 then CASE WHEN aaproces.manmatno3 = '' THEN ssproces.matno3 ELSE aaproces.manmatno3 END
end)
JOIN dbo.aaprocqt on aaprocqt.estno = aaproces.estno and aaprocqt.procgroup = aaproces.procgroup
and aaproces.partno = aaprocqt.partno and aaproces.[lineno] = aaprocqt.[lineno]
and aaproces.counter = aaprocqt.counter and aaprocqt.qty = v_est_joblist.alt
WHERE aaproces.procgroup <> 'I'
--and sq.CopyNum < 4
and case when sq.CopyNum = 1 then (manmatno + matno1 )
when sq.CopyNum = 2 then (aaproces.manmatno2 + ssproces.matno2 )
when sq.CopyNum = 3 then (manmatno3 + matno3 )
end <> ''
AND v_est_joblist.ljob = #tcLjob
--------------------------------------------------------------------------- STOCKS (ESTIMATED)
UNION ALL
SELECT #tcLjob, coalesce(case when aastocks.houvend = 'H' then ssinvent.deptno
else case when aapthead.parttype = 'S' then #opt_stockccs
else #opt_stockccr end end,'????')
as deptno,
CASE WHEN coalesce((SELECT v_depuse_qty.DepUse FROM dbo.v_depuse_qty WHERE v_est_joblist.estno = v_depuse_qty.estno
AND v_depuse_qty.deptno = ssdept.deptno
AND V_DEPUSE_QTY.LJOB = V_EST_JOBLIST.LJOB
AND V_DEPUSE_QTY.ALT = V_EST_JOBLIST.ALT), 1) = 1 THEN CASE WHEN #tcCostBase = 'D' THEN
CASE WHEN aastocks.houvend = 'V' THEN (1 / (1 + (ssdept.burden/100)))
ELSE (1 / (1 + (ssinvent.burden/100))) END
ELSE 1 END *
case when v_est_joblist.alt = 1 then aastocks.stkcost1 * aastocks.cartonratio1
when v_est_joblist.alt = 2 then aastocks.stkcost2 * aastocks.cartonratio2
when v_est_joblist.alt = 3 then aastocks.stkcost3 * aastocks.cartonratio3
when v_est_joblist.alt = 4 then aastocks.stkcost4 * aastocks.cartonratio4
when v_est_joblist.alt = 5 then aastocks.stkcost5 * aastocks.cartonratio5
END
ELSE 0
END AS ecostmats,
0 as ecostlab,
0 as eprochours,
0 AS bcostmats,
0 AS bcostlab,
0 AS bprochours,
0.0 AS acostmats,
0.0 AS acostlab,
0 AS aprochours,
0.0 AS chgcost,
0 AS dirlab,
0.0 AS aacost,
0.0 AS pecost,
0.0 AS otcost,
0 AS sell
FROM dbo.aapthead
INNER JOIN dbo.aastocks on aapthead.estno = aastocks.estno and aapthead.partno = aastocks.partno
INNER JOIN dbo.v_est_joblist on v_est_joblist.estno = aapthead.estno
LEFT OUTER JOIN dbo.ssinvent on aastocks.matno = ssinvent.matno
AND ssinvent.invtype IN ('R', 'S')
LEFT OUTER JOIN dbo.ssdept ON ssdept.deptno = (CASE WHEN aastocks.houvend = 'H' THEN ssinvent.deptno
ELSE CASE WHEN aapthead.parttype = 'S' THEN #opt_stockccs
ELSE #opt_stockccr
END
END)
WHERE v_est_joblist.ljob = #tcLjob
AND 1 = [dbo].[DivisionCheck] (ssdept.divno,#tcDivNo)
In the three code samples shown, I see nothing that would generate that subquery error message.
exists() subqueries are designed to handle multilple returned rows
The select max() subquery is properly formed
There is nothing that would cause problems if the only subquery in the third block returned multiple rows
Ergo, it must be something else. My guess—and this is a guess—is that, in the third bock, tables v_est_joblist and/or v_depuse_qty are in fact views (I use something like the v_Blah convention myself), and something’s going wrong in one of them. If so, you’d need to test these views, see what they’re returning when joined into the main query as they are.
It appears that your "in" expression is being supplied with more than one row of values. So, although "exists" can accept multiple rows as input, "0 in (aastk.cartonratio1, ...) cannot.

Query conversion from sybase to SQL Server

I have one query that is to convert from sybase to SQL server, I think we just need to change join operations.. Here is part of the query:
Can someone help me here?
FROM sy_trcr_divided d, fd_income_trans t
WHERE d.fd_id_income is not null
AND t.fd_income_transfer_id = d.fd_proc_id
AND t.fd_income_est_yn = 'Y'
AND d.fd_id_income = a.fd_id
AND d.fd_dist_to_i_or_p = 'A'
AND d.gl_year = :p_lYear
AND d.gl_period = :p_lPeriod
AND d.fd_include_stip_yn = 'Y'),0) AS ADDTO_FUND
FROM sy_est_income_detail a,
fd_master
WHERE a.fd_id *= fd_master.fd_id and
a.hr_id = :p_szHRID
My thought: have to replace *= with a join.
The *= should be a left join and the piece of the query you provided should probably be:
FROM sy_trcr_divided d
INNER JOIN fd_income_trans t ON t.fd_income_transfer_id = d.fd_proc_id
WHERE d.fd_id_income is not null
AND t.fd_income_est_yn = 'Y'
AND d.fd_id_income = a.fd_id
AND d.fd_dist_to_i_or_p = 'A'
AND d.gl_year = :p_lYear
AND d.gl_period = :p_lPeriod
AND d.fd_include_stip_yn = 'Y'),0) AS ADDTO_FUND
FROM sy_est_income_detail a
LEFT JOIN fd_master ON a.fd_id = fd_master.fd_id
WHERE a.hr_id = :p_szHRID

Converting T-SQL Left Join Subqueries to MS-Access

I need help in converting this T-SQL query to MS ACCESS. The error that I'm getting is JOIN expression not supported.
Update:
I can't add:
DDA ON TT.[Description] = DDA.AccountTypeDesc AND
H.AccountNumber = DDA.AccountNumber
But
DDA ON TT.[Description] = DDA.AccountTypeDesc
works. Is there a way to add the second condition?
T-SQL Query:
SELECT
*
FROM
(
SELECT
[PesoAmount] = CASE WHEN FE.IsoCode IS NULL THEN
LTRIM(STR(DFCF.CurrencyAmount, 20, 2))
ELSE
LTRIM(STR(DFCF.CurrencyAmount * FE.PhpConversionRate, 20, 2))
END,
DFCF.TransactionNumber,
DFCF.AccountNumber,
DFCF.CountryCd,
DFCF.TransactionTypeCd,
DFCF.Time,
DFCF.Date,
DFCF.TransactionStatusCd,
DFCF.TransactionCurrencyCd,
DFCF.BranchNumber,
DFCF.RemitterExtPartyCd,
DFCF.BeneficiaryExtPartyCd,
DFCF.PostedDate,
DFCF.AssociateNumber,
DFCF.ExecutingPartyNumber,
DFCF.CurrencyAmount,
DFCF.CurrencyAmountInTxnCcy,
DFCF.CurrencyAmountInAccountCcy,
DFCF.SecondaryAccountKey,
DFCF.RelatedInd,
DFCF.ThirdPartyInd,
DFCF.TransactionDescription,
DFCF.SecurityName,
DFCF.DealNumber
FROM
dbo.DesFactCashFlow DFCF (NOLOCK) LEFT JOIN
dbo.ForeignExchange FE (NOLOCK) ON DFCF.TransactionCurrencyCd = FE.IsoCode
)
H LEFT JOIN
dbo.Ctr C (NOLOCK) ON H.PesoAmount = C.PesoAmountFaceValueSumInsured AND
H.AccountNumber = C.AccountNumber AND
H.TransactionTypeCd = C.TransactionType LEFT JOIN
dbo.TransactionType TT (NOLOCK) ON H.TransactionTypeCd = TT.Code LEFT JOIN
(
SELECT
[AccountNumber] = DDA2.AccountNumber,
[AccountTypeDesc] = DDA2.AccountTypeDesc,
[LineOfBusinessName] = MAX(DDA2.LineOfBusinessName),
[AccountCurrencyCode] = MAX(DDA2.AccountCurrencyCode),
[AccountCurrencyName] = MAX(DDA2.AccountCurrencyName),
[AccountRegistrationTypeDesc] = MAX(DDA2.AccountRegistrationTypeDesc),
[AccountRegistrationName] = MAX(DDA2.AccountRegistrationName),
[AccountName] = MAX(DDA2.AccountName),
[AlternateName] = MAX(DDA2.AlternateName),
[AccountOpenDate] = MAX(DDA2.AccountOpenDate),
[AccountCloseDate] = MAX(DDA2.AccountCloseDate),
[AccountStatusDesc] = MAX(DDA2.AccountStatusDesc),
[DormantInd] = MAX(DDA2.DormantInd),
[ProductLineName] = MAX(DDA2.ProductLineName),
[ProductCategoryName] = MAX(DDA2.ProductCategoryName),
[ProductTypeName] = MAX(DDA2.ProductTypeName),
[ProductName] = MAX(DDA2.ProductName),
[ProductNumber] = MAX(DDA2.ProductNumber),
[AccountTaxId] = MAX(DDA2.AccountTaxId),
[AccountTaxIdTypeCode] = MAX(DDA2.AccountTaxIdTypeCode),
[AccountTaxStateCode] = MAX(DDA2.AccountTaxStateCode),
[AccountPrimaryBranchName] = MAX(DDA2.AccountPrimaryBranchName),
[MailingAddress1] = MAX(DDA2.MailingAddress1),
[MailingAddress2] = MAX(DDA2.MailingAddress2),
[MailingCityName] = MAX(DDA2.MailingCityName),
[MailingStateCode] = MAX(DDA2.MailingStateCode),
[MailingStateName] = MAX(DDA2.MailingStateName),
[MailingPostalCode] = MAX(DDA2.MailingPostalCode),
[MailingCountryCode] = MAX(DDA2.MailingCountryCode),
[MailingCountryName] = MAX(DDA2.MailingCountryName),
[CurrencyBasedAccountInd] = MAX(DDA2.CurrencyBasedAccountInd),
[MaturityDate] = MAX(DDA2.MaturityDate),
[OriginalLoanAmount] = MAX(DDA2.OriginalLoanAmount),
[CollateralTypeDesc] = MAX(DDA2.CollateralTypeDesc),
[CollateralTypeCode] = MAX(DDA2.CollateralTypeCode),
[InsuredAmount] = MAX(DDA2.InsuredAmount),
[EmployeeInd] = MAX(DDA2.EmployeeInd)
FROM
dbo.DesDimAccount DDA2 (NOLOCK)
GROUP BY
DDA2.AccountNumber,
DDA2.AccountTypeDesc
)
DDA ON RTRIM(TT.[Description]) = RTRIM(DDA.AccountTypeDesc) AND
H.AccountNumber = DDA.AccountNumber
EDIT: I replaced the query with the AS keyword. I get the same error.
MS Access Query with Error:
SELECT
'H' AS [HeaderRecordIndicator],
'1' AS [SupervisingAgency],
'0' + I.InstitutionCode AS [InstitutionCode],
CONVERT(char(8), H.Date, 112) AS [ReportDate],
'CTR' AS [ReportType],
'21' AS [FormatCode],
'1' AS [SubmissionType]
FROM
(((
SELECT
IIF(ISNULL(FE.IsoCode), FORMAT(DFCF.CurrencyAmount, "##################.00"), FORMAT(DFCF.CurrencyAmount * FE.PhpConversionRate, "##################.00")) AS [PesoAmount],
DFCF.TransactionNumber,
DFCF.AccountNumber,
DFCF.CountryCd,
DFCF.TransactionTypeCd,
DFCF.Time,
DFCF.Date,
DFCF.TransactionStatusCd,
DFCF.TransactionCurrencyCd,
DFCF.BranchNumber,
DFCF.RemitterExtPartyCd,
DFCF.BeneficiaryExtPartyCd,
DFCF.PostedDate,
DFCF.AssociateNumber,
DFCF.ExecutingPartyNumber,
DFCF.CurrencyAmount,
DFCF.CurrencyAmountInTxnCcy,
DFCF.CurrencyAmountInAccountCcy,
DFCF.SecondaryAccountKey,
DFCF.RelatedInd,
DFCF.ThirdPartyInd,
DFCF.TransactionDescription,
DFCF.SecurityName,
DFCF.DealNumber
FROM
DesFactCashFlow DFCF LEFT JOIN
ForeignExchange FE ON DFCF.TransactionCurrencyCd = FE.IsoCode
) AS
H LEFT JOIN
Ctr C ON H.PesoAmount = C.PesoAmountFaceValueSumInsured AND
H.AccountNumber = C.AccountNumber AND
H.TransactionTypeCd = C.TransactionType) LEFT JOIN
TransactionType TT ON H.TransactionTypeCd = TT.Code) LEFT JOIN
(
SELECT
DDA2.AccountNumber AS [AccountNumber],
DDA2.AccountTypeDesc AS [AccountTypeDesc],
MAX(DDA2.LineOfBusinessName) AS [LineOfBusinessName],
MAX(DDA2.AccountCurrencyCode) AS [AccountCurrencyCode],
MAX(DDA2.AccountCurrencyName) AS [AccountCurrencyName],
MAX(DDA2.AccountRegistrationTypeDesc) AS [AccountRegistrationTypeDesc],
MAX(DDA2.AccountRegistrationName) AS [AccountRegistrationName],
MAX(DDA2.AccountName) AS [AccountName],
MAX(DDA2.AlternateName) AS [AlternateName],
MAX(DDA2.AccountOpenDate) AS [AccountOpenDate],
MAX(DDA2.AccountCloseDate) AS [AccountCloseDate],
MAX(DDA2.AccountStatusDesc) AS [AccountStatusDesc],
MAX(DDA2.DormantInd) AS [DormantInd],
MAX(DDA2.ProductLineName) AS [ProductLineName],
MAX(DDA2.ProductCategoryName) AS [ProductCategoryName],
MAX(DDA2.ProductTypeName) AS [ProductTypeName],
MAX(DDA2.ProductName) AS [ProductName],
MAX(DDA2.ProductNumber) AS [ProductNumber],
MAX(DDA2.AccountTaxId) AS [AccountTaxId],
MAX(DDA2.AccountTaxIdTypeCode) AS [AccountTaxIdTypeCode],
MAX(DDA2.AccountTaxStateCode) AS [AccountTaxStateCode],
MAX(DDA2.AccountPrimaryBranchName) AS [AccountPrimaryBranchName],
MAX(DDA2.MailingAddress1) AS [MailingAddress1],
MAX(DDA2.MailingAddress2) AS [MailingAddress2],
MAX(DDA2.MailingCityName) AS [MailingCityName],
MAX(DDA2.MailingStateCode) AS [MailingStateCode],
MAX(DDA2.MailingStateName) AS [MailingStateName],
MAX(DDA2.MailingPostalCode) AS [MailingPostalCode],
MAX(DDA2.MailingCountryCode) AS [MailingCountryCode],
MAX(DDA2.MailingCountryName) AS [MailingCountryName],
MAX(DDA2.CurrencyBasedAccountInd) AS [CurrencyBasedAccountInd],
MAX(DDA2.MaturityDate) AS [MaturityDate],
MAX(DDA2.OriginalLoanAmount) AS [OriginalLoanAmount],
MAX(DDA2.CollateralTypeDesc) AS [CollateralTypeDesc],
MAX(DDA2.CollateralTypeCode) AS [CollateralTypeCode],
MAX(DDA2.InsuredAmount) AS [InsuredAmount],
MAX(DDA2.EmployeeInd) AS [EmployeeInd]
FROM
DesDimAccount DDA2
GROUP BY
DDA2.AccountNumber,
DDA2.AccountTypeDesc
) AS
DDA ON RTRIM(TT.[Description]) = RTRIM(DDA.AccountTypeDesc) AND
H.AccountNumber = DDA.AccountNumber
Here is the simplified query with the same error:
SELECT
*
FROM
(((
SELECT
IIF(ISNULL(FE.IsoCode), FORMAT(DFCF.CurrencyAmount, "##################.00"), FORMAT(DFCF.CurrencyAmount * FE.PhpConversionRate, "##################.00")) AS [PesoAmount],
DFCF.TransactionNumber,
DFCF.TransactionCurrencyCd,
FROM
DesFactCashFlow DFCF LEFT JOIN
ForeignExchange FE ON DFCF.TransactionCurrencyCd = FE.IsoCode
) AS
H LEFT JOIN
Ctr C ON H.PesoAmount = C.PesoAmountFaceValueSumInsured AND
H.AccountNumber = C.AccountNumber AND
H.TransactionTypeCd = C.TransactionType) LEFT JOIN
TransactionType TT ON H.TransactionTypeCd = TT.Code) LEFT JOIN
(
SELECT
DDA2.AccountNumber AS [AccountNumber],
DDA2.AccountTypeDesc AS [AccountTypeDesc],
MAX(DDA2.LineOfBusinessName) AS [LineOfBusinessName],
FROM
DesDimAccount DDA2
GROUP BY
DDA2.AccountNumber,
DDA2.AccountTypeDesc
) AS
DDA ON RTRIM(TT.[Description]) = RTRIM(DDA.AccountTypeDesc) AND
H.AccountNumber = DDA.AccountNumber
Give up trying to convert the SQL text from your T-SQL query to Access SQL. Create a new Access query from scratch and use the T-SQL query only as a road map. Add your data sources and set up the joins. The query designer will guarantee you create the joins in the manner which keeps the db engine happy: addition and positioning of parentheses it requires for queries with more than one join; the rules which apply for LEFT JOINs; and so forth. Just let the designer handle those details for you.
The designer will choke in Design View due to the functions in this part of your last join:
RTRIM(TT.[Description]) = RTRIM(DDA.AccountTypeDesc)
So leave out the RTRIM() functions while you're setting up the joins in Design View. Don't worry that the query doesn't return the correct results. After you get joins which satisfy the db engine, switch to SQL View and add the RTRIM() functions back in.
After you get the joins set up correctly, then add in your field expressions to the SELECT list.
Also you may find it easier to manage your complex query by breaking out the subqueries as separate saved queries --- then reference those queries by name in the master query just as you would table sources.
The problem is with the penultimate line:
DDA ON RTRIM(TT.[Description]) = RTRIM(DDA.AccountTypeDesc) AND
The Design View of the Access query designer can't work with functions in the ON part of the clause. You must remove the RTRIM.
Access is parenthesis happy. Wrap each join expression in parentheses, the ON clauses themselves, and each pair of tables.
You can't use CONVERT, NOLOCK, or CASE.
Which version of MSAccess you are using in your system? I just tried in 2007 version and RTRIM is working.

How to get all values including null in a SQL Server case statement?

I have a big stored procedure, and basically I want to select all values (including null) if my variable #DimBrowserId is set to 0. I am using a case statement, however this is only catching values that actually have something and ignoring the NULL valued fields. Because I am using the = clause in the WHERE I cannot do IS NULL. I do not want to have to write 2 IF statements because the stored procedure would then be enormous, so I want to know how to get null values as well. Here is my code:
SELECT
DATEPART(yy, DATEADD(mi, #Mdelta, d.DimDateValue)),
DisableCount = COUNT(*)
FROM
dbo.FactDisable AS f
JOIN
dbo.DimDate AS d ON f.DimDateId = d.DimDateId
JOIN
dbo.DimDevice AS v ON f.DimDeviceId = v.DimDeviceId
WHERE
d.DimDateValue >= #StartDateGMT
AND d.DimDateValue <= #EndDateGMT
AND f.IsTest = #IncludeTest
AND f.DimProductId = #DimProductId
AND v.DimBrowserId = CASE
WHEN #DimBrowserId = 0 THEN v.DimBrowserId
ELSE #DimBrowserId
END
GROUP BY
DATEPART(yy, DATEADD(mi, #Mdelta, d.DimDateValue))
The code is near the CASE clause.
Thanks
Change that line to be
AND (#DimBrowserID = 0 OR #DimBrowserID = v.DimBrowserId)
If #DimBroserID is 0 then no filtering will be applied for this line.
Use ISNULL:
SELECT DATEPART(yy,DATEADD(mi,#Mdelta,d.DimDateValue)),
DisableCount=COUNT(*)
FROM dbo.FactDisable AS f
JOIN dbo.DimDate AS d ON f.DimDateId = d.DimDateId
JOIN dbo.DimDevice AS v ON f.DimDeviceId = v.DimDeviceId
WHERE d.DimDateValue >= #StartDateGMT AND d.DimDateValue <= #EndDateGMT
AND f.IsTest = #IncludeTest AND f.DimProductId = #DimProductId
AND v.DimBrowserId = CASE WHEN ISNULL(#DimBrowserId,0) = 0 THEN v.DimBrowserId ELSE #DimBrowserId END
GROUP BY DATEPART(yy,DATEADD(mi,#Mdelta,d.DimDateValue))
CASE WHEN COALESCE(#MightBeNull, 0) = 0 THEN ZeroResult ...
will be treated as zero if #MightBeNull is null, and whatever #MightBeNull is if it's not null.
Assuming null means any browser, a better data model for this scenario might be to set an ID that identifies any browser, instead of setting it to null.
You probably know what you are running into is NULL does not equal NULL in a comparison.
Assuming you don't have control of the data model to fix that, one option would be to coalesce your NULL values to an unused id.
The resulting WHERE clause would look like this, assuming -1 is the unused value you choose.
AND COALESCE(v.DimBrowserId, -1) = CASE WHEN #DimBrowserId = 0 THEN COALESCE(v.DimBrowserId, -1) ELSE #DimBrowserId END

Resources