在SELECT FROM循环中传递变量

时间:2017-09-02 13:30:59

标签: sql-server variables while-loop fetch

我希望从多个表(MainTbl)中进行选择,但它将基于将拉出表的结果集(StateTbl)。

MainTables dbo.TABLE_MOdbo.TABLE_CAdbo.TABLE_ALdbo.TABLE_MI

仅根据结果集StateTbl MOCAWA

进行拉取
Declare @Loop_Count int = 0
DECLARE @State varchar(2)
DECLARE @SQL varchar(max)

DECLARE db_cursor CURSOR FOR SELECT State FROM StateTbl

OPEN db_cursor

FETCH db_cursor INTO @State

WHILE (@@FETCH_STATUS = 0) 
BEGIN 


SET @SQL = 
'
    dbo.TABLE_'+ @State +'
'
EXEC(@SQL)

SET @Loop_Count = @Loop_Count + 1
FETCH db_cursor INTO @SQL

END
CLOSE  db_cursor
DEALLOCATE db_cursor

1 个答案:

答案 0 :(得分:1)

您可以利用dynamic和StateTbl来构建动态sql,而不是循环。这样的事情。

declare @SQL nvarchar(max) = ''

select 'select * from TABLE_' + [State] + ' UNION ALL '
from StateTbl

select @SQL = left(@SQL, len(@SQL) - 10)

select @SQL
--uncomment the line below when you satisfied the dynamic sql is written the way you want it.
--exec sp_executesql @SQL