简体   繁体   中英

Multiple values in a cursor which executes a stored procedure

I have a cursor which executes a stored procedure. I have introduced a new variable dbname into the cursor and I get an exception error near dbname. This change was introduced so that the stored procedure storedProc_getOutputsByRuncan be executed on different databases.

#

exec( '
DECLARE @dbName nvarchar(100)
DECLARE @runID INT
DECLARE @getRunDetails CURSOR
DECLARE @delayLoad bigint
SET @delayLoad = 1
SET @getRunDetails = CURSOR FOR
SELECT DBName, RunID from ' + @temp_table_runID + '
OPEN @getRunDetails
FETCH NEXT
FROM @getRunDetails INTO @dbName, @runID
WHILE @@FETCH_STATUS = 0
BEGIN
-- I have tried at this point printing @runid and @dbname and it prints fine.Error in line below
INSERT INTO ' + @temp_table_outputs + ' Execute ''@dbname''.dbo.storedProc_getOutputsByRun        
@runID, @delayLoad
FETCH NEXT
FROM @getRunDetails INTO @dbName, @runID
END
CLOSE @getRunDetails
DEALLOCATE @getRunDetails')

If you were to wrap all this up in its own variable, and print it, this line

'INSERT INTO ' + @temp_table_outputs + ' Execute ''@dbname''.dbo.storedProc_getOutputsByRun'

Would yield something like this:

INSERT INTO myTable Execute '@dbname'.dbo.storedProc_getOutputsByRun

The problem being you're not escaping the string correctly to replace @dbname with an actual value.

The fix would be to nest another string within the main string, and execute that.

Something like this INSIDE the main string:

declare @sql nvarchar(max)
set @sql = ''INSERT INTO ' + @temp_table_outputs + ' Execute ''+@dbname+''.dbo.storedProc_getOutputsByRun ''+cast(@runID as varchar)+'', ''+cast(@delayLoad as varchar)+''''
print @sql
exec(@sql)

Which would yield a final product similar to this...

exec( '
DECLARE @dbName nvarchar(100)
DECLARE @runID INT
DECLARE @getRunDetails CURSOR
DECLARE @delayLoad bigint
SET @delayLoad = 1
SET @getRunDetails = CURSOR FOR
SELECT DBName, RunID from ' + @temp_table_runID + '
OPEN @getRunDetails
FETCH NEXT
FROM @getRunDetails INTO @dbName, @runID
WHILE @@FETCH_STATUS = 0
BEGIN
    declare @sql nvarchar(max)
    set @sql = ''INSERT INTO ' + @temp_table_outputs + ' Execute ''+@dbname+''.dbo.storedProc_getOutputsByRun ''+cast(@runID as varchar)+'', ''+cast(@delayLoad as varchar)+''''
    print @sql
    --exec(@sql)  


    FETCH NEXT
    FROM @getRunDetails INTO @dbName, @runID
END
CLOSE @getRunDetails
DEALLOCATE @getRunDetails')

You may need to tweak this a bit, but this is easy now, just comment out the EXEC(@SQL) as I have done inside the new code, and print it out to screen. Copy the messages to a new SSMS window, and check the syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM