简体   繁体   中英

Can i have multiple select but only return one result set

If I have multiple selects like so:

select * from A where A.name = 'linköping'

IF @@ROWCOUNT = 0
begin
    select * from A where A.amount = 45
end

...I get 1 result set if the first select returns stuff. But if it runs the second, I get two result sets; the first with no rows and the second with some rows.

Is there a way to only return the second result set if the second select is run ?

I write code like this because of Andrey Gordeev's answer to this post: Can you have if-then-else logic in SQL?

(MSSQL 2000)

Thanks!

You will need to prevent the first select by checking if you will get any results back before running the select.

For example:

IF EXISTS (SELECT 1 FROM A WHERE A.name = 'linköping')
BEGIN
    SELECT * FROM A WHERE A.name = 'linköping'
END
ELSE 
BEGIN
    SELECT * FROM A WHERE A.amount = 45
END

This will work with IF-ELSE Logic. [Tested]

DECLARE @count as int
set @count = (SELECT count(1) from A where A.name = 'linköping')
if (@count = 0)
BEGIN
    select * from A where A.amount = 45
END
ELSE
BEGIN
select * from A where A.name = 'linköping'
END

No it is not possible The returning results are depending on number of select statements. If you want to do the single select follow @RB or @Jwalin Shah solution.

Try this

IF @@ROWCOUNT = 0
BEGIN
    select * from A where A.amount = 45
END
ELSE
BEGIN
    select * from A where A.name = 'linköping'
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM