我有这个选择查询:
SELECT CASE
WHEN (
SELECT isnull((
SELECT max(SeqNo)
FROM tblReconBankAccountHODetail
WHERE BankAccountID = '0MA27'
AND BusinessDate = '3/12/2018 12:00:00 AM'
), '0')
) = '0'
THEN (
SELECT max(SeqNo) + 1
FROM tblReconBankAccountHODetail
WHERE BankAccountID = '0MA27'
AND BusinessDate = '3/12/2018 12:00:00 AM'
)
ELSE '1'
END SeqNo
当我选择
时,我试图根据几种条件来获取SeqNo
的行号
SELECT isnull(SELECT max(SeqNo) FROM tblReconBankAccountHODetail WHERE BankAccountID = '0MA27')
它会给我结果147,这是正确的,我想做的是,如果该行存在,它将给我第二个查询的行计数+1。这意味着147 + 1为{{1 }},如果该行不存在,则会给我结果:148
但我的查询始终返回1
,如果我删除了1
,我的查询将返回then '1'
。我的查询在哪里做错了?
答案 0 :(得分:1)
我能够通过声明我在此查询中设置的变量@counter
来解决这个问题
SELECT ISNULL(MAX(SeqNo), 0) FROM tblReconBankAccountHODetail WHERE BankAccountID = '0MA27' AND BusinessDate = '3/12/2018 12:00:00 AM')
然后在查询时将@counter
放在大小写中:
CASE WHEN @counter= 0
THEN 1
ELSE @counter+1
END SeqNo
向@MichałTurczyn喊叫以获取更简洁的查询
更新:
SELECT CASE
WHEN (select isnull((SELECT max(SeqNo) from tblReconBankAccountHODetail where BankAccountID = '0MA27' and BusinessDate = @rc),'0')) != 0
THEN (SELECT max(SeqNo)+1 from tblReconBankAccountHODetail where BankAccountID = '0MA27' and BusinessDate = @rc)
else 1
END SeqNo
上面的查询也可以
答案 1 :(得分:0)
您的查询有几个问题:
SQL语法使用大写字母,但它不是必需的,因为它不区分大小写。使用大写或小写,但要保持一致!不要混。
正确的缩进大大简化了查询(以及一般代码)的查找和理解。
这里是重构查询:
SELECT CASE WHEN (SELECT ISNULL(MAX(SeqNo), 0) FROM tblReconBankAccountHODetail
WHERE BankAccountID = '0MA27' AND BusinessDate = '3/12/2018 12:00:00 AM') = 0
THEN (SELECT MAX(SeqNo) + 1 FROM tblReconBankAccountHODetail
WHERE BankAccountID = '0MA27' AND BusinessDate = '3/12/2018 12:00:00 AM')
ELSE 1 END SeqNo
您的问题是,您将VARCHAR
数据类型与INT
混合在一起。
此行:
select isnull((SELECT max(SeqNo) from tblReconBankAccountHODetail
where BankAccountID = '0MA27' and BusinessDate = '3/12/2018 12:00:00 AM'),'0')
根据您的信息,将始终返回整数:147,然后将其与'0'
的{{1}}进行比较,从而得到意外的结果。
但是,如果内部查询不返回任何行,则该查询将无法工作,因此我建议以下做法:
CHAR(1)
甚至更简单:
SELECT CASE WHEN (SELECT COUNT(*) FROM tblReconBankAccountHODetail
WHERE BankAccountID = '0MA27' AND BusinessDate = '3/12/2018 12:00:00 AM') = 0
THEN (SELECT COUNT(*) + 1 FROM tblReconBankAccountHODetail
WHERE BankAccountID = '0MA27' AND BusinessDate = '3/12/2018 12:00:00 AM')
ELSE 1 END SeqNo