简体   繁体   中英

Issue executing Dynamic sql query

I have a SQL set of instructions that I want to execute across multiple databases. I currently have the following SQL code:

USE Database1

DECLARE @mySourceTable AS [someUserDefinedType];
/*Execute set of operations on Database 1 and @mySourceTable*/

DECLARE @dbList TABLE (DBName nvarchar(50));

INSERT INTO @dbList (DBName)
VALUES('Database2'),('Database3');

DECLARE @dbName nvarchar(50);

DECLARE dbCursor CURSOR FOR SELECT DBName FROM @dbList;

OPEN dbCursor;
FETCH NEXT FROM dbCursor INTO @dbName;

WHILE @@FETCH_STATUS = 0
BEGIN
    EXECUTE('USE ' + @dbName + N'; 

    DECLARE @content AS [someUserDefinedType];

    INSERT INTO @content (ID)
    SELECT ID FROM '+ @mySourceTable + N';

    EXECUTE dbo.someProcedure @content;'); 

    FETCH NEXT FROM dbCursor INTO @dbName;
END;

CLOSE dbCursor;
DEALLOCATE dbCursor;

Basically I want to do the following: I have several databases that all have the same [someUserDefinedType] table type (with the same structure) and a procedure named dbo.someProcedure that receives as a parameter a table of said type (the dbo.someProcedure is not the same across databases, it is specific to each). I want to go through the list of provided databases ( @dbList ) and execute each stored procedure with data from @mySourceTable . I am not sure if the code above is the best approach, it does not work and gives the error:

Must declare the scalar variable "@mySourceTable".

This variable is already declared at the beginning of the script. What am I doing wrong? Is it possible to pass the data from @mySourceTable using a variable and not create another table for it (I really want to avoid that)?

Try something like this:

USE Database1

DECLARE @mySourceTable AS [someUserDefinedType];
/*Execute set of operations on Database 1 and @mySourceTable*/

DECLARE @dbList TABLE (DBName nvarchar(50));

INSERT INTO @dbList (DBName)
VALUES('Database2'),('Database3');

DECLARE @dbName nvarchar(50);

DECLARE dbCursor CURSOR FOR SELECT DBName FROM @dbList;

OPEN dbCursor;
FETCH NEXT FROM dbCursor INTO @dbName;

DECLARE @DynamicTSQLStatement NVARCHAR(MAX);

WHILE @@FETCH_STATUS = 0
BEGIN

    SET @DynamicTSQLStatement = N'

    USE ' + @dbName + '; 

    DECLARE @content AS [someUserDefinedType];

    INSERT INTO @content (ID)
    SELECT ID FROM @mySourceTable;

    EXECUTE dbo.someProcedure @content;'; 

    FETCH NEXT FROM dbCursor INTO @dbName;

    EXEC sp_executesql  @DynamicTSQLStatement, N'@mySourceTable someUserDefinedType readonly', @mySourceTable =  @mySourceTable

END;

CLOSE dbCursor;
DEALLOCATE dbCursor;

When you are executing T-SQL statement with sp_executesql you can pass parameters.

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