views:

28

answers:

1

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 (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?

A: 

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...

gbn