T-SQL Declaring Connection String as a Parameter

我与影子孤独终老i 提交于 2020-02-25 05:20:46

问题


DECLARE @DBS nvarchar(32)
SET @DBS = 'Current' --'Archive'
SELECT TOP 100 *
  FROM [@DBS].[dbo].[table]

I have 2 structurally identical databases that sit on the same server. One only saves information for 30 days, for quick report processing, the other saves years worth of information. Either query executes fine if I have Current.dbo.table or Archive.dbo.table, but I'm wanting to set a parameter so we can toggle between Current and Archive, within the same report, so a user can pull from the Archive database without having to have admin access to switch the data source connection string. Is this possible to do? I'm certain the syntax error is because the connection string is not a nvarchar, but I can't figure out the proper way to write this query.


回答1:


For SQL Server you'll need Dynamic SQL.

DECLARE @DBS nvarchar(32)
SET @DBS = 'Current' --'Archive'
DECLARE @SQL VARCHAR(MAX)
SET @SQL = '
SELECT TOP 100 *
  FROM ' + @DBS + '.[dbo].[table]'
EXEC(@SQL)



回答2:


you can try this. Based on your parameter value the individual selects return either all rows or nothing.

SELECT TOP 100 *
  FROM [DBS].[dbo].[table] -- Your active table schema
 where @yourParamenter= 0
union
SELECT TOP 100 *
  FROM [archiveDBS].[dbo].[table]   -- Your archive table schema
 where @yourParamenter= 1


来源:https://stackoverflow.com/questions/40475582/t-sql-declaring-connection-string-as-a-parameter

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