3

Given different machines with sql server. All of them have the same databases. The only difference between these db's is their name. It could be two names, let's say 'DB1' and 'DB2'.

I need to check, which name is used on the given machine and create a function over it. The function is pretty big, it has at least 50 spots where the name of the DB is needed.

I was trying to do something like

DECLARE @dbName VARCHAR(20)
SET @dbName = ISNULL(DB_ID('DB1'), 'DB2');

SELECT * FROM @dbName.dbo.testtable;

But it does not work. Any help would be appreciated.

Dzmitry Sevkovich
  • 871
  • 1
  • 8
  • 16

4 Answers4

3

No, that won't work. With only two possible database you may be better off with an if:

DECLARE @dbName VARCHAR(20)
SET @dbName = CASE WHEN DB_ID('DB1') IS NULL THEN 'DB2' ELSE 'DB1' END;

IF @dbName = 'DB1' 
    SELECT * FROM DB1.dbo.testtable;
ELSE
    SELECT * FROM DB2.dbo.testtable;

If you want to run ALL future queries in that scope against that database then dynamically run a USE statement instead:

IF @dbName = 'DB1' 
    USE DB1;
ELSE
    USE DB2;
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • So basically, if I have 100 references to one of these db's, I have to use that if-else for each reference. Correct? – Dzmitry Sevkovich Dec 09 '13 at 17:22
  • @DzmitrySevkovich if all of the queries are in the same scope than you can use a `USE` statement to change the database - see my edit. – D Stanley Dec 09 '13 at 17:29
  • @D Stanley unfortunately, it gave me an error: a USE database statement is not allowed in a procedure, function or trigger. – Dzmitry Sevkovich Dec 09 '13 at 17:42
  • Can you choose the database before running the procedure? The procedure should then run using that database. – D Stanley Dec 09 '13 at 19:25
2

You can use dynamic SQL:

DECLARE @dbName VARCHAR(20)
SET @dbName = 'DB2'

IF DB_ID('DB1') IS NOT NULL
    SET @dbName = 'DB1'

DECLARE @SQL NVARCHAR(100)
SET @SQL = N'SELECT * FROM ' + @dbName + N'.dbo.testtable'

EXEC sp_executesql @SQL
Paul Williams
  • 16,585
  • 5
  • 47
  • 82
1

You may try like this using the DB_ID function:

IF DB_ID('DB1') IS NOT NULL
PRINT 'exists'

Try like this:

DECLARE @db VARCHAR(20)
SET @db = CASE WHEN DB_ID('DB1') IS NULL 
          THEN 'DB2' 
          ELSE 'DB1'
          END;

IF @db = 'DB1' 
    SELECT * FROM DB1.dbo.testtable;
ELSE
    SELECT * FROM DB2.dbo.testtable;
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0
DECLARE @dbName NVARCHAR(128);
DECLARE @Sql NVARCHAR(MAX);
SET @dbName = 'DataBaseName'


IF db_id(@dbName) is not null

   BEGIN    
       SET @Sql = N'SELECT * FROM ' + QUOTENAME(@dbName) + N'.[dbo].[TableName]'   
   END

ELSE

  BEGIN
    SET @Sql = N'SELECT * FROM ' + QUOTENAME(db2Name) + N'.[dbo].[TableName]'
  END 

EXECUTE sp_Executesql @Sql
M.Ali
  • 67,945
  • 13
  • 101
  • 127