0

I basically have a query with a @date parameter, and depending on that @date I want to run a query against the proper table. If it matters, the tables are the same structure but on 2 different servers however they are linked so running from either is not an issue. So I'm looking to:

IF @date = getdate() THEN
SELECT * FROM server1.db1..MyTable
ELSE
SELECT * FROM server2.db2..MyTable_history WHERE date = @date
END

I'm pretty sure this can be done with dynamic sql, but the query is a little hairy so I would like to avoid that if possible. I was hoping to just be able to do something very clean like a big IF ELSE statement - run one query or the other.

Any help would be appreciated. Also I'm using SQL Server 2008 R2

Thank you!

3
  • 1
    Rather than a single procedure it would be best from a performance perspective if you create one procedure as your "driver" that has the IF conditions. Then inside the conditions you call separate procedures. The pattern you are describing is known as multiple execution paths. Gail Shaw has a great article on the topic here. sqlinthewild.co.za/index.php/2009/09/15/… Commented Apr 20, 2016 at 16:53
  • 1
    You just need to cast(getdate() as date) and change the then to begin and it should do what you need. Commented Apr 20, 2016 at 17:09
  • Thanks Martin, this worked! I've tried this a few times in the past, but embarassingly enough I must have just had the IF BEGIN END syntax wrong all this time! Commented Apr 20, 2016 at 17:26

1 Answer 1

1

Try this:

IF @date = CAST(getdate() as date)
BEGIN 
SELECT * FROM server1.db1..MyTable
ELSE
SELECT * FROM server2.db2..MyTable_history WHERE date = @date
END
Sign up to request clarification or add additional context in comments.

1 Comment

Yes this is what Martin suggested above, it worked, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.