i want to union query from multiple database. but before union i want to check if database exits then un开发者_如何学Cion, if second database exits then union and so on...
IF EXISTS(SELECT * FROM sys.sysdatabases where name='FirstDB')
select * from FirstDB.dbo.tablename
union
IF EXISTS(SELECT * FROM sys.sysdatabases where name='SecondDB')
select * from SecondDB.dbo.tablename.
How to do that. Thanks in advance.
If a database is missing (don't quite understand) the batch will not compile therefore the code will not run. This means any tests for database existence will fail.
Assuming you really have databases appearing and disappearing randomly, the only "practical" option is dynamic SQL
...
IF DB_ID('FirstDB') IS NOT NULL
SET @sql ='select * from FirstDB.dbo.tablename'
IF DB_ID('SecondDB') IS NOT NULL
SET @sql = @sql + CASE WHEN @sql = '' THEN '' ELSE 'union ' END +
'select * from SecondDB.dbo.tablename'
...
Selecting databases or tables on runtime is code smell. It might be valid in your case, but it's certainly suspect. If you have any control over the databases being used, consider re-evaluating your database design. Are databases created and destroyed on runtime? That is almost certainly a bad idea.
Define a view with a fixed name in each server: In FirstDB server:
CREATE DATABASE SOME_DATABASE;
CREATE VIEW SOME_DATABASE.FIXED_TABLENAME AS SELECT * FROM FirstDB.dbo.tablename
In SecondDB server:
CREATE DATABASE SOME_DATABASE;
CREATE VIEW SOME_DATABASE.FIXED_TABLENAME AS SELECT * FROM SecondDB.dbo.tablename
In code in either DB:
SELECT * FROM SOME_DATABASE.FIXED_TABLENAME;
精彩评论