我希望从多个表(MainTbl)中进行选择,但它将基于将拉出表的结果集(StateTbl)。
MainTables dbo.TABLE_MO
,dbo.TABLE_CA
,dbo.TABLE_AL
,dbo.TABLE_MI
仅根据结果集StateTbl MO
,CA
,WA
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
答案 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