I have a cursor that gets data and fetches it into @data_table. Then in the while loop I want to pass that @data_table into another cursor (as the table name) to run some more processing. I keep getting a declare @data_table error. How do I fix this?
DECLARE @var_name varchar(50)
DECLARE @data_table varchar(50)
DECLARE @data_value varchar(50)
DECLARE curDiscreteVars CURSOR LOCAL
FOR SELECT DISTINCT v.var_name, v.data_table
FROM dbo.vars v
GROUP BY v.var_name, v.data_table
-- Loop through cursor, translating variable values as needed, and generate counts for each val_code for a variable
OPEN curDiscreteVars
FETCH NEXT FROM curDiscreteVars
INTO @var_name, @data_table
WHILE @@FETCH_STATUS = 0
BEGIN
--loop through all possible data values
DECLARE curValues CURSOR LOCAL
FOR SELECT DISTINCT @var_name
FROM @data_table
OPEN curValues
FETCH NEXT FROM curValues
INTO @data_value
WHILE @@FETCH_STATUS = 0
BEGIN
print @var_name
FETCH NEXT FROM curValues
INTO @data_value
END
CLOSE curValues
DEALLOCATE curValues
FETCH NEXT FROM curDiscreteVars
INTO @var_name, @data_table
END
CLOSE curDiscreteVars
DEALLOCATE curDiscreteVars
I’m not sure I understand what you’re talking about doing, but variables cannot be used as table names. Or, really anything that’s not a field name. You’ll need to use dynamic SQL. That is, assign your SQL string to a variable, an then run
EXEC()command.For example:
Alternately, if what you mean is that you need a location to store the data that is like a table, then create a temporary tabled for it.