I'm looking to select from multiple tables (MainTbl) but it will be based on the result set (StateTbl) of which tables would be pulled.
MainTables dbo.TABLE_MO, dbo.TABLE_CA, dbo.TABLE_AL, dbo.TABLE_MI
Only looking to pull based on resultset 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
EXEC(@SQL)supposed to select from a table?@SQLwill only contain the name of a table. Shouldn't you be doingSET @SQL = 'SELECT * FROM dbo.TABLE_'+ @State +' '?