我有一个返回多个结果集的存储过程,它看起来像这样
BEGIN
SET NOCOUNT ON;
SELECT c1, c2, c3
FROM t1
WHERE id = @id
IF (@@ROWCOUNT = 0)
BEGIN
SELECT c1, c2, c3
FROM t2
WHERE id = @id
END
END
我在前端ASP.NET网站中使用此存储过程。
如果第一个SELECT语句没有返回任何行,我在SqlDataReader中得到2个结果集(第一个显然为空)。 有没有办法只返回上一个SELECT语句的结果集?
答案 0 :(得分:3)
您可以在这里选择几个选项,您必须在您的环境中进行测试,看看哪种方法效果最好。
第一个选项是将第一个语句包装在if块中,类似于您对第二个块所做的操作:
BEGIN
SET NOCOUNT ON;
if exists
(
SELECT c1, c2, c3
FROM t1
WHERE id = @id
)
begin
SELECT c1, c2, c3
FROM t1
WHERE id = @id
end
else
begin
SELECT c1, c2, c3
FROM t2
WHERE id = @id
END
END
第二个选项是使用临时表/变量:
BEGIN
SET NOCOUNT ON;
declare @t1 table (c1 int, c2 int, c3 int)
insert @t1 (c1,c2,c3)
SELECT c1, c2, c3
FROM t1
WHERE id = @id
IF (@@ROWCOUNT = 0)
BEGIN
SELECT c1, c2, c3
FROM t2
WHERE id = @id
END
ELSE
BEGIN
select c1,c2,c3
from @t1
end
END
答案 1 :(得分:3)
与其他好的答案略有不同,您可以使用联合:
SELECT c1, c2, c3 FROM t1 WHERE id = @id
UNION ALL
SELECT c1, c2, c3 FROM t2 WHERE id = @id
AND NOT EXISTS (
SELECT * FROM t1 WHERE id = @id
)
答案 2 :(得分:1)
DECLARE @Count int;
SELECT @Count = Count(*)
FROM t1
WHERE id = @id
IF(@Count = 0)
BEGIN
SELECT c1, c2, c3
FROM t2
WHERE id = @id
END
ELSE
BEGIN
SELECT c1, c2, c3
FROM t1
WHERE id = @id
END
答案 3 :(得分:1)
保持简单:
BEGIN
SET NOCOUNT ON;
if exists (SELECT 1 FROM t1 WHERE id = @id)
SELECT c1, c2, c3
FROM t1
WHERE id = @id
else
SELECT c1, c2, c3
FROM t2
WHERE id = @id
END
答案 4 :(得分:0)
;
WITH
rws_1 AS(
SELECT c1, c2, c3 FROM t1 WHERE id = @id
),
rws_2 AS(
SELECT c1, c2, c3 FROM t2 WHERE id = @id
)
SELECT * FROM rws_1
UNION ALL
SELECT * FROM rws_2 WHERE NOT EXISTS(SELECT * FROM rws_1)