开发者

Execute queries until non-empty result

I have three queries, looking like these:

SELECT * FROM Table1 WHERE Column1 = 'a'
SELECT * FROM Table2 WHERE Column2 = 'b'
SELECT * FROM Table1 A, Table2 B WHERE A.Column1 <> B.Column1

Now all logic is implemented on the client side as following. Execute the first query, if HasRows, set a flag to 1 and return the rows. Otherwise execute the second query, if HasRows, set the flag to 2 and return the 开发者_运维问答rows. Otherwise execute the third query, set the flag to 3 and return the rows.

How to do this with a single query? Flag stuff, I guess, should be solved adding Flag to the queries:

SELECT Flag = 1, * FROM Table1 WHERE Column1 = 'a'
SELECT Flag = 2, * FROM Table2 WHERE Column2 = 'b'
SELECT Flag = 3, * FROM Table1 A, Table2 B WHERE A.Column1 <> B.Column1

But now what? How to check, if a query returns non-empty result?

Also, I'd like to cache the results, in other words, to avoid executing the same query twice - once for checking and the second time - for returning data.

Regards,


You could use a table variable to store the result and only return it at the end of the SQL block. Checking @@rowcount would tell you if the previous insert added any rows; if it's zero, you can run further queries:

declare @result table (flag int, col1 int, col2 varchar(50))
insert @result select 1, col1, col2 from Table1 where Column1 = 'a'
if @@rowcount = 0 
    begin
    insert @result select 2, col1, col2 from Table2 where Column1 = 'b'
    end
if @@rowcount = 0 
    begin
    insert @result select 3, col1, col2 from Table1 A, Table2 B 
        where A.Column1 <> B.Column1
    end

select * from @result

This approach only works if each select has the same column definition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜