tags:

views:

301

answers:

1

Hi

I want to query across multiple databases in SQL Server, so I thought I could create a variable called @DBNAME and pass it to a query as follows (but it doesn't work).

This will be inside a loop where DBNAME is stepped through as a count on dbid.. my count works and it prints out @DBNAME as all of the production databases.. but I can't get it to query across multiple databases!

IF EXISTS (SELECT 1 FROM @DBNAME.INFORMATION_SCHEMA.TABLES

WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='DataArea') SELECT 'GETIN' AS res ELSE SELECT 'aaargh' AS res --SELECT * From DataArea AS res ELSE SELECT NULL AS res;

+6  A: 

You can do it with dynamic sql like this

declare @tablename as sysname, @dbname as sysname
select 
@dbname = 'master', 
@tablename = 'dbo.spt_fallback_db'
declare @script nvarchar(4000)
select @script = 'select top 10 * from ' + @dbname + '.' + @tablename
exec sp_executesql @script

Substitute your database and table names as appropriate. Just used one form master for testing purposes.

u07ch
Thanks for the help. I have declared the following as my @script variable:select @script = "SELECT 1 FROM ' + @DBNAME + '.' + @tablename + ' WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='DataArea'"I think it's fine with this, but when add the following, it doesn't like the execIF EXISTS exec sp_executesql @scriptit says Msg 156, Level 15, State 1, Line 20Incorrect syntax near the keyword 'exec'.
Instead of exec ... do select @script and you will see the final script that SQL will try and process
u07ch
It's not having it:Invalid column name 'SELECT 1 FROM ' + @DBNAME + '.' + @tablename + ' WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='DataArea''.
The idea is the script you build up in the variable @script is something that is valid to run. From what you have posted it may be missing spaces between elmentse.g ... from ' and ' where... '
u07ch