0

I have multiple databases and their names are in masterDBTable.

MasterDBTable

ID DBName

  1. CustomerDB1

  2. CustomerDB2

  3. CustomerDB3

In each of these DB's, there's a table called clients

How would I loop through and insert all the clients from each DB into a temp table? When I try I get the following error:

"variable assignment is not allowed in a cursor declaration."

Here's an example:

DECLARE @DataBaseName VARCHAR
    ,@SQL NVARCHAR

CREATE TABLE #TempClient (ClientName VARCHAR(50))

DECLARE clients CURSOR FAST_FORWARD READ_ONLY
FOR
SELECT DISTINCT @DataBaseName = DataBaseName
FROM AIMS.DataBaseMaster

OPEN clients

FETCH NEXT
FROM clients
INTO @DataBaseName

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @SQL = 'INSERT INTO #TempClient(ClientName)
     SELECT ClientName FROM ' + @DataBaseName + '.[Example].[Clients]'

    EXECUTE sp_executesql @SQL
END

CLOSE clients

DEALLOCATE clients

SELECT *
FROM #TempClient

1 Answer 1

1

You need to remove the variable here:

SELECT DISTINCT  @DataBaseName = DataBaseName
          FROM AIMS.DataBaseMaster 

to

SELECT DISTINCT  DataBaseName
          FROM AIMS.DataBaseMaster 

Also

after

EXECUTE sp_executesql @SQL

add

   FETCH NEXT FROM clients INTO @DataBaseName

to get the next element in the cursor

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.