Query against two tables in separate databases on the same server
I need to query two tables in two different databases on the same SQL Se开发者_如何学Gorver
. On one table, I need to get all the rows (simple select) and on the other, a select but where the id matches a parameter in my stored proc.
I tried doing this but get the error
The multi-part identifier could not be bound.
How can I go about this?
QUERY:
SELECT QUALITY_CENTER, POSTCODE_ID, (SELECT [QCID]
FROM [Website_Interactive].[dbo].[IIPCentre_UserObject]
WHere LoginID = @loginID)
FROM IIP_QC_LIST
Sounds like you mistyped something. You can query a table in another DB using the following method:
SELECT tn.ID, tn.NAME
FROM [Database Name].[Schema].[TableName] as tn
I purposely added a two word database name because you have to put square brackets around that for it to be recognized. Your Schema will most likely be dbo
.
If you show us your query and give us the DB names I can provide a more complete answer.
UPDATE:
Are you sure you are spelling "Center" correctly? I noticed you spelled it "centre" in IIPCentre_UserObject
which I think might be right for the UK (?) but you spelled it "center" for QUALITY_CENTER
. I would assume it's spelled one way or the other in your environment.
You can easily do that by providing the FQN (Fully Qualified Name) to the SQL object (in this case your SQL table). The FQN syntax for a table is as such:
[database-name].[schema-name].[table-name]
Example:
SELECT a, b, c FROM Database1.Schema1.Table1
UNION
SELECT a, b, c FROM Database2.Schema2.Table2
Where Database1 is your first database and Database2 is your second.
It's possible/straightforward to select from different databases on the same server. You need to use a fully qualified name i.e.
SELECT * from database.schema.table
For example
SELECT * FROM northwind.dbo.orders where id = @id
You can query two separate database if the table from 1 database is the same value with another table
like these:
SELECT * FROM DB1.dbo.MyTable db1,DB2.dbo.MyTable db2 where db1.table1=db2.table1
精彩评论