Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i have multiple select but only return one result set

Tags:

sql

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!

like image 304
Cotten Avatar asked Feb 28 '13 09:02

Cotten


People also ask

Can you have two SELECT statements?

To combine two or more SELECT statements to form a single result table, use the set operators: UNION, EXCEPT or INTERSECT. For example, assume that you have the following tables to manage stock at two book stores.

Can we use two SELECT IN sql?

In reality it is not possible to put both tables into one and have a new "team" column.

How do you use multiple SELECT?

Definition and Usage For windows: Hold down the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.

What is the difference between SELECT and SELECT All?

SELECT ALL means ALL rows, i.e including duplicate rows. (The opposite is SELECT DISTINCT , where duplicate rows are removed.) ALL is the default, and most people write just SELECT instead of SELECT ALL . SELECT * means all columns.


1 Answers

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
like image 197
RB. Avatar answered Feb 13 '23 02:02

RB.