Hi,i've got the following problem: I want to execute a query in multiple databases on my Server. For every customer that i have, there is a db. Those dbs all have exactly the same table and their names are similar. So there is a db kde_01_Miller, then a kde_02_Mueller and so on ...I want to execute a query in every one of those dbs.Here's what i tried:DECLARE @name VARCHAR(100) -- database nameDECLARE @dothis nvarchar(200)DECLARE db_cursor CURSOR FORSELECT nameFROM master.dbo.sysdatabasesWHERE name like 'kde_0%'order by nameOPEN db_cursor FETCH NEXT FROM db_cursor INTO @name WHILE @@FETCH_STATUS = 0BEGIN set @dothis = 'use [' + @name + ']' exec sp_executesql @dothis /* Start query */ select description from dbo.basicdata /* End query */ FETCH NEXT FROM db_cursor INTO @name END CLOSE db_cursor DEALLOCATE db_cursor
The problem is, that the query does not work properly. The use-statement seems not to be working. I get a result for every database i have, but the result is always the same one, dependent on the database, i'm currently doing a query for.I've also tried the following and it worked: Instead of my while-loop i did this:WHILE @@FETCH_STATUS = 0BEGIN set @dothis= 'select description from ' + QUOTENAME(@name) + '.dbo.basicdata' exec sp_executesql @dothis FETCH NEXT FROM db_cursor INTO @name END
But i don't like this way, because you need the quotename(@name) for every table.How do i make the first example work?