Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 245
  • Last Modified:

Conditionally accesing a possibly non existent table from other DB


Hi, I have a SELECT in a stored procedure that access a table in a database distinct of the
database where this SELECT is, by means of a LEFT JOIN:

SELECT
    A.id, B.id
FROM
     A LEFT JOIN OTHER_DB.dbo.B ON A.Id = B.Id

the thing is, OTHER_DB may not exist, and I want to know if it is possible to use conditional
compilation (or another solution), to have a code that can be used whether that other db exists or
not (using only table A in case OTHER_DB doesn't exists); the only way I can think is simply put
the code that references that db enclosed in commentary marks like this:

SELECT
    A.id--, B.id
FROM
     A --LEFT JOIN OTHER_DB.dbo.B ON A.Id = B.Id

but I'm curious if other more seamless or practical way is possible, in order to maintain more
easily my code, I'm not sure if it possible something like that... thanks in advance.

0
GHR_GDL
Asked:
GHR_GDL
1 Solution
 
JestersGrindCommented:
Typically a left join is used to perform a conditional join.  Your situation is a little different because the table may or may not exist.  There are two ways that I can think of that might work.  You could have two versions of the query in your stored procedure, one with the table and without.  And then, use IF EXISTS(SELECT * FROM sys.databases WHERE name = OTHER_DB) query with OTHER_DB ELSE query without OTHER_DB.

The other way is to use dynamic SQL and build your select statement based on whether the database exists or not.

Greg

0
 
GHR_GDLAuthor Commented:
Lead me to try other stuff that worked for me.
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now