Select from multiple databases

They have: 82 posts

Joined: Oct 2001

Hey guys,

I have a SQL Server database with two databases in it.

Let's call them database1 and dataase 2.
I need a query that selects data from table1 in both databases.
How would I accomplish this?

Select field1
from database1.table1,
database2.table1
where something is =something

Also I need to build the database name for a query from a string
i.e. Org_xxxx where xxxx is passed in as a parameter.

Set DBName= 'Org_" + Cast(xxxx, as char(4)
any ideas?

Thanks

- Mike Ross

Blessed is the man who fears the LORD, who delights greatly in his commandments. Psalms 112:1

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

Concept sounds right. Did you try it and get an error?

They have: 82 posts

Joined: Oct 2001

Yup get an error on all of it.

Thanks

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

can you copy&paste the errors? (and code)

Peter J. Boettcher's picture

They have: 812 posts

Joined: Feb 2000

I think you have to use a union and make sure whatever connection string you're using has the right permissions in both databases. To be on the safe side try adding the owner of the objects, for example:

SELECT field1 FROM database1.dbo.table1 WHERE something IS something

UNION

SELECT field1 FROM database2.dbo.table1 WHERE something IS something

ORDER BY field1

PJ | Are we there yet?
pjboettcher.com

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.