开发者

Re-run the query of store the results in a table variable?

I am in a situation where I need to run multiple times the same queries. I have to look if one of the rows returned correspond to a specific value (query 1) otherwise, I have to return the first row of the result set (query 2). In SQL Server 2008, I am wondering what is best: running the query and storing the results in a table variable or re-running the query twice 开发者_Python百科(i.e. SELECT * FROM Bla WHERE Bla.Column IN (...) and SELECT TOP 1 * FROM Bla)?

Which of the two solution is preferable and/or faster?


Nothing "clean" to be honest, really

SELECT * INTO #foo FROM Bla WHERE Bla.Column IN (...)
IF @@ROWCOUNT = 0 
    SELECT TOP 1 * FROM Bla
ELSE
    SELECT * FROM #foo

The aim of this snippet

  • to touch Bla as few times as possible
  • return one recordset

It could be done in one UNION ALL with NOT IN or EXISTS too, but this means more touches on Bla.

I'm not sure if this your option 1 or 2...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜