我在存储过程中有一系列与UNION连接的查询。如果他们都没有返回值,即。 Rowcount = 0然后我想让查询在其中一个文本字段中显示“No Records”
我的联盟后面有以下内容,但它作为两个单独的查询,因此得到2组结果。我需要只有一个,我尝试将这个结合起来没有运气,因为我认为它没有正确计数,因为当它作为联合的一部分运行时查询没有完成。
任何帮助都会很棒。
IF (@@ROWCOUNT = 0)
BEGIN
SELECT NULL AS [Date/Time]
,NULL AS [Event ID]
,NULL AS [Action Performed By]
,NULL AS [Action Performed On]
,NULL AS [Action]
,'No records balh balh' AS [Entitlement Being Changed]
,NULL AS [Description of Change]
,NULL AS [Application Name]
,NULL AS [Machine Name]
END
答案 0 :(得分:3)
虽然我衷心同意X-Zero,但以下是一个可怕的例子:
declare @Stuff as table ( Thing varchar(16) )
insert into @Stuff ( Thing ) values ( 'Congress' ), ( 'Progress' ), ( 'Oxymoron' )
declare @SelectNought as Bit = 1 -- Flip me!
; with Aleph as (
( select Thing, 0 as Flag
from @Stuff where Thing like 'C%' and @SelectNought = 0
union all
select Thing, 0 as Flag
from @Stuff where Thing like 'P%' and @SelectNought = 0
union all
select Thing, 0 as Flag
from @Stuff where Thing like 'O%' and @SelectNought = 0 ) ),
Beth as (
select * from Aleph
union all
select 'Nope', 1 )
select Thing from Beth where Flag = ( case when exists ( select * from Beth where Flag = 0 ) then 0 else 1 end )
我要强调:不要去这里!
答案 1 :(得分:2)
简单地说“不要这样做”并不是特别有用。
假设没有UI,并且您需要返回的数据集以某种方式确认没有找到匹配的记录而不是简单地为空,那么您可以尝试使用临时表。
在存储过程中,将union查询的结果选择到临时表中。然后检查临时表中是否有现有记录,并返回临时表的内容或默认的“未找到”记录。
答案 2 :(得分:1)
我同意X-Zero。如果数据库调用没有结果,请让UI处理向用户显示的内容。如上所述,这是一个UI功能,并不是分离关注点的最佳实践。