1

I want to write query in which name table will dynamicaly compute. I have code like this below. What should I put in 'magic code' region?

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

I use MS SQL Server 2012

4

2 回答 2

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
于 2013-04-25T13:15:53.550 回答
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 允许参数化查询 - 检查其文档

于 2013-04-25T13:19:27.267 回答