不了解Coalesce的工作原理?

时间:2014-03-10 15:37:14

标签: sql oracle coalesce

我以为我理解coalesce在oracle中是如何工作的,但由于某种原因,这个简单的select语句并没有提出它应该是什么。我对coalesce的理解是它遍历括号中的所有值,直到它达到它正在查看的字段中的值。在我的代码中,select中的两个帐户都有一个rr.rel_type的Customer2。我通过查看racctrel中的值来仔细检查这一点。当我运行代码时,结果为零。这是代码:

SELECT lt.ACCOUNT, 
       rr.rel_type,
       lt.transaction_date, 
       lt.amount, 
       lt.transaction_code, 
       ltc.fintran_tran_code, 
       fo.FIRM_NAME AS ATTORNEY, 
       lt.debtor_ssn, 
       REPLACE(rr.NAME,';',',') AS DEBTOR_NAME, 
       lt.description AS COST_DESCRIPTION,
       pd.owner
FROM legal_transactions lt, 
     legal_transaction_codes ltc, 
     firms_onboarded fo, 
     racctrel rr,
     package_details pd,
     raccount ra
WHERE fo.attorney_id = lt.attorney_id
AND rr.ACCOUNT = lt.ACCOUNT
AND ra.ACCOUNT = lt.ACCOUNT
and pd.package_id = ra.user_text_3
AND ltc.transaction_code = lt.transaction_code
AND lt.batch_id = 865
AND upper(rr.rel_type) = coalesce('CUSTOMER1','PRIMDEBTOR','CUSTOMER2')
AND lt.ACCOUNT IN ('17149146','17918854');

SELECT account, rel_type
FROM racctrel
where ACCOUNT IN ('17149146','17918854');

结果是:

17918854    Customer2
17149146    Customer2

2 个答案:

答案 0 :(得分:4)

实际上,它的工作原理应该是:

这里

AND upper(rr.rel_type) = coalesce('CUSTOMER1','PRIMDEBTOR','CUSTOMER2')

COALESCE的结果是'CUSTOMER1' - 首先不是空值,而这里是

17918854    Customer2
17149146    Customer2

您只有'CUSTOMER2'

所以它是正确的:

AND upper(rr.rel_type) = coalesce('CUSTOMER1','PRIMDEBTOR','CUSTOMER2')

=> 

AND 'CUSTOMER2' = 'CUSTOMER1'

是假的。

答案 1 :(得分:2)

coalesce返回第一个not-null参数,如果所有参数都是NULL,则返回NULL。因此coalesce('CUSTOMER1','PRIMDEBTOR','CUSTOMER2')始终评估为'CUSTOMER1'。您可能需要的是IN条款。而不是

AND upper(rr.rel_type) = coalesce('CUSTOMER1','PRIMDEBTOR','CUSTOMER2')

AND upper(rr.rel_type) in ('CUSTOMER1','PRIMDEBTOR','CUSTOMER2')