Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

c# - Joining between multiple databases

Update I get an Invalid object name error for the DataBaseA.dbo.templates

I wish to Inner join two tables from seperate databases on the same server (Local).

But i can't seem to get it work. Also i don't understand how i should be handling my connectionstring, as i'm currently setting the current connection to the connectionstring of my database. But in this example i'm trying to connect to two different databases in the same query.

This is my SQL code so far:

"SELECT a.template.*, b.c_template.* FROM DatabaseA.dbo.templates a INNER JOIN DatabaseB.dbo.c_template b ON a.id = b.template_id"

And this is my connectionstrings:

<add name="Unit" connectionString="Data Source=(LocalDB)v11.0;AttachDbFilename=|DataDirectory|DatabaseA.mdf;Integrated Security=True"
        providerName="System.Data.SqlClient" />
    <add name="Content" connectionString="Data Source=(LocalDB)v11.0;AttachDbFilename=|DataDirectory|DatabaseB.mdf;Integrated Security=True"
        providerName="System.Data.SqlClient" />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do you know If the table "templates" has the schema owner as "dbo" or It is something else. Can you execute the following query and see If you find the table?

SELECT * FROM Unit.dbo.templates.

If you don't find the table, you should use the the following command to find out the schema owner:-

Use [Unit]
Go
sp_help templates

In the below example, the schema owner is dbo. When you execute yours, you would see some other schema owner (e.g xyz). Use that schema owner.

SELECT * FROM Unit.xyz.template

enter image description here

If you are still not able to find the table, It sounds like the default database for the query from the application is set to the database where the table "tenplate" does not exist. Can you try using a different form of connection string. "myUsername" in the below connection string should have same required privileges to both DatabaseA And DatabaseB:-

Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword; 

Example :-

Server=localDBv11.0;Database=DataBaseA;User Id=UserA;Password=UserAPassword; 

Create a database user named "UserA" and have appropriate access to both DatabaseA and DatabaseB.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...