justuptime.com - monitor your servers & websites

Select from multiple databases

You are viewing this site as a guest. Join our community to get your questions answered and share knowledge. Active members may advertise and ask for a website critique.

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,044 posts

Joined: Aug 2000

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

Mark Hensler ["Max Albert"] [Email]
If there is no answer on Google, then there is no question.

They have: 82 posts

Joined: Oct 2001

Yup get an error on all of it.

Thanks

Mark Hensler's picture

He has: 4,044 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