SQL - run query against different table (dynamic table) based on parameter

女生的网名这么多〃 提交于 2020-01-17 13:47:19

问题


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!


回答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


来源:https://stackoverflow.com/questions/36750253/sql-run-query-against-different-table-dynamic-table-based-on-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!