从具有动态计算名称的表中选择

时间:2013-04-25 13:05:39

标签: sql sql-server

我想编写名称表将动态计算的查询。我有这样的代码如下。我应该把什么放在“魔法代码”区域?

DECLARE @myTableName nvarchar(100) = 'sch' 
         +  CAST(@nowYear as VARCHAR(5)) 
         +  'Q' 
         +  CAST(@nowQuarter as VARCHAR(3)) 
         +  '.[tVisits]'

-- magic code --
myTable = DoSomething(@aktTableName)   
-- magic code --

SELECT * FROM myTable

我使用MS SQL Server 2012

2 个答案:

答案 0 :(得分:2)

您需要使用动态SQL -

DECLARE 
      @nowYear INT = 2013
    , @nowQuarter INT = 1

DECLARE @myTableName NVARCHAR(100) = '[sch' 
         +  CAST(@nowYear AS VARCHAR(5)) 
         +  'Q' 
         +  CAST(@nowQuarter AS VARCHAR(3)) 
         +  '].[tVisits]'

DECLARE @SQL NVARCHAR(MAX) = N'SELECT * FROM ' + @myTableName

EXEC sys.sp_executesql @SQL

答案 1 :(得分:0)

而不是SELECT * FROM myTable

您需要执行类似

的操作
DECLARE @sql nvarchar(4000)
SELECT @sql = ' SELECT * FROM ' + @myTable -- @myTable is a string containing qualified table name
EXEC sp_executesql @sql

请注意,sp_executesql允许参数化查询 - 请检查its documentation