Query with Two Different DSN - dsn

I have a query:
<asp:SqlDataSource runat="server" ID="SqlDataSource1"
ConnectionString="Dsn=Xdb;uid=xxx;pwd=xxxxxxx" ProviderName="System.Data.Odbc"
SelectCommand="SELECT XReqOrders.LoadNum, XReqOrders.StopSeq, XRecPkgs.DeliveryTime,
XRecActivity.Address, XReqOrders.OrderOrTripOrRGA, XReqPkgs.Barcode,
XReqPkgs.Description, XRecPkgs.IsDelivered, XRecPkgs.IsOnStop, YDelInfo.DeliveryDate
FROM (((XReqOrders INNER JOIN XReqPkgs ON XReqOrders.LoadNumberOrderNumber = XReqPkgs.LoadNumberOrderNumber)
LEFT JOIN XRecPkgs ON XReqPkgs.Barcode = XRecPkgs.Barcode)
LEFT JOIN XRecActivity ON XRecPkgs.TranId = XRecActivity.TranId)
INNER JOIN YDelInfo ON XReqOrders.OMID = YDelInfo.OMID
ORDER BY XReqOrders.StopSeq, XRecPkgs.DeliveryTime">
</asp:SqlDataSource>
The "X" tables are from one data source and the "Y" table is from another...but there is join between the data sources. I can't seem to figure out how to enter the two different connection strings for this to run.
ConnectionString="Dsn=Xdb;uid=xxx;pwd=xxxxxxx" ProviderName="System.Data.Odbc"
ConnectionString="Dsn=Ydb;uid=xxx;pwd=xxxxxxx" ProviderName="System.Data.Odbc"
Is this possible...am I just missing something?

You can't JOIN tables from two different databases. Depending upon what database engine you're using, you might be able to set up a "virtual" or "linked" table in one database that points to a table in the other database, and do a JOIN that way. Otherwise, your only choice is to make a copy of the table you need to JOIN to in the other database, and JOIN to the copy.

The actual database query is run on the server side, not client side, so there's no "quick and easy" way to join the two tables.
Possible options are:
1) Set up a "Linked Server" (MSSQL term, not sure what the corresponding term would be in MySql or Oracle, or even if they're supported) on one of the SQL servers that points to the other server.
2) Do the individual selects separately into business objects, and then do the join in your business logic instead of in the database, either manually spinning through the records in for loops or utilizing a technology like LINQ in .NET.

As others have said you would have to set-up a "Linked Server"

Related

OPENDATASOURCE (Transact-SQL) - Connecting to multiple tables

I have a use case for OPENDATASROUCE. However, my SQL query has multiple tables with left joins.
Most of the examples have one table only. How I connect in case I have 2 tables (2nd table has left join)
Below is a typical example and working great:
SELECT *
FROM OPENDATASOURCE('SQLNCLI', 'Data Source=RemoteServerName;Integrated Security=SSPI').Billing.dbo.Invoices
But I need to join invoices table with 'customer' table like below. I am not sure how I do that?? Please help
SELECT *
FROM OPENDATASOURCE('SQLNCLI', 'Data Source=RemoteServerName;Integrated Security=SSPI').Billing.dbo.Invoices as inv
left join Billing.dbo.customers as cust
on inv.customer = cust.customer
OPENDATASOURCE is one way to talk to a remote server using the "linked server" or "distributed query" functionality in SQL Server. However, it is not likely the best path for you to use in this case as it does not allow for the SQL Server Query Optimizer to rewrite the query and push parts of the query down to the remote source (potentially reducing the number of rows returned to you over a slower network connection vs. your local database). If possible, creating an actual linked server would help you here. This would give you the option to say to the optimizer "these two tables are from the same remote source". Then the optimizer can consider plans that remotes a single query to the remote server that joins those two tables together, applies any filters and group by clauses, and then returns the result to the calling server.
Here's the mechanism to add a linked server:
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-addlinkedserver-transact-sql?view=sql-server-2017
Once you have a remote server (which I'll call "remote" here), you can write the query using the 4-part name syntax for remote servers instead of using OPENDATASOURCE.
SELECT * FROM REMOTE.Billing.DBO.Invoices LEFT JOIN REMOTE.Billing.DBO.Invoices on <join condition> <WHERE clause>
Here is a paper on how linked servers work under the covers which should give you a conceptual overview as to why this approach is likely better for you:
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.59.8007
Best of luck!

How can I get data from 2 different SQL Servers

I have the following situation. I am working with 2 separate SQL servers. Server A hosts the company HR data. There is a view on Server a that provides supervisor info for each employee. I need to get the next supervisor info going up the chain. So I used this to code, I got from the DB admin, to accomplish that
SELECT *
FROM [lawdata].[dbo].[All_Users] ru1
left outer join [lawdata].[dbo].[All_Users] ru2 on ru1.SUPER_EID = ru2.EMP_EID
Now I have data on a separate SQL Server, Server B, that contains some report data the ReportData table contains the employee ID which matches employee ID numbers shown in the view above from Server A. The questions is how can I merge the view from Server A and the Employee ID on Server B so I can link the supervisors to the data rows on Server B.
I have seen this post but just cannot get the syntax right to make it work with my situation
Thanks
You need linked servers. then use
[ServerName].[DatabaseName].[dbo].[tableName]
Create Linked Servers (SQL Server Database Engine)
For this, I'd create an SSIS package to pull down the data from the lawdata server into the database on Server B once a night - probably just a truncate and reload. This way, all of your queries with lawdata data on Server B is localized to one database on one server.
it looks like in your code you did a left outer join on something with itself. Try
SELECT *
FROM [server1].[dbname].[dbo].[tablename] A
left outer join [server2].[dbname].[dbo].[tablename] B on A.columnname = B.columnname
where ["insert where clause here"]
Just in case someone else is trying to solve this same problem here is the solution I came up with; thanks to the suggestion given above
select rd.*, ru1.emp_first, ru1.emp_last, ru1.Super_Last as FirstLineLast,
Super_first as FirstLineFirst,
ru2.Super_Last as SecondLineLast,
2.Super_first as SecondLineFirst
from [TaserEvidence].[dbo].[ReportData] rd left outer join
[soops-lawrept].[lawdata].[dbo].[My_View] ru1 on rd.OwnerBadgeId = ru1.emp_EID
left outer join
[soops-lawrept].[lawdata].[dbo].[rob_users] ru2 on ru1.super_EID = ru2.EMP_EID

SQLAlchemy: Multiple databases (on the same server) in a single session?

I'm running MS SQL Server and am trying to perform a JOIN between two tables located in different databases (on the same server). If I connect to the server using pyodbc (without specifying a database), then the following raw SQL works fine.
SELECT * FROM DatabaseA.dbo.tableA tblA
INNER JOIN DatabaseB.dbo.tableB tblB
ON tblA.id = tblB.id
Unfortunately, I just can't seem to get the analog to work using SQLAlchemy. I've seen this topic touched on in a few places:
Is there a way to perform a join across multiple sessions in sqlalchemy?
Cross database join in sqlalchemy
How do I connect to multiple databases on the same SQL Server with sqlalchemy?
How can I use multiple databases in the same request in Cherrypy and SQLAlchemy?
Most recommend to use different engines / sessions, but I crucially need to perform joins between the databases, so I don't think this approach will be helpful. Another typical suggestion is to use the schema parameter, but this does not seem to work for me. For example the following does not work.
engine = create_engine('mssql+pyodbc://...') #Does not specify database
metadataA = MetaData(bind=engine, schema='DatabaseA.dbo', reflect=True)
tableA = Table('tableA', metadataA, autoload=True)
metadataB = MetaData(bind=engine, schema='DatabaseB.dbo', reflect=True)
tableB = Table('tableB', metadataB, autoload=True)
I've also tried varients where schema='DatabaseA' and schema='dbo'. In all cases SQLAlchemy throws a NoSuchTableError for both tables A and B. Any ideas?
If you can create a synonym in one of the databases, you can keep your query local to that single database.
USE DatabaseB;
GO
CREATE SYNONYM dbo.DbA_TblA FOR DatabaseA.dbo.tableA;
GO
Your query then becomes:
SELECT * FROM dbo.DbA_TblA tblA
INNER JOIN dbo.tableB tblB
ON tblA.id = tblB.id
I'm able to run a test just like this here, reflecting from two remote databases, and it works fine.
Using a recent SQLAlchemy (0.8.3 recommended at least)?
turn on "echo='debug'" - what tables is it finding?
after the reflect all, what's present in metadataA.tables metadataB.tables?
is the casing here exactly what's on SQL server ? (e.g. tableA). Using a case sensitive name like that will cause it to be quoted.

How can I use two different databases with Linq to SQL in Linqpad?

I'm starting out with Linq To SQL, fiddling around with Linqpad and I'm trying to duplicate a SQL script which joins on tables in separate databases on the same server (SQL Server 2008).
The TSQL query looks approximately like this:
using MainDatabase
go
insert Event_Type(code, description)
select distinct t1.code_id, t2.desc
from OtherDatabase..codes t1
left join OtherDatabase..lookup t2 on t1.key_id = t2.key_id and t2.category = 'Action 7'
where t2.desc is not null
I'm basically trying to figure out how to do a cross-database insertion. Is this possible with Linq To SQL (and is it possible in Linqpad?)
This is possible in LINQ to SQL if you create a (single) typed DataContext that contains table classes for objects in both databases. This designer won't help you here, so you have to create some of the table classes manually. In other words, use the VS designer to create a typed DataContext for your primary database, then manually add classes for the tables in the other database that you wish to access:
[Table (Name = "OtherDatabase.dbo.lookup")]
public class Lookup
{
...
}
Edit: In LINQPad Premium edition, you can now do cross-database queries with SQL Server - in one of two ways.
The simplest is the drag-and-drop approach: hold down the Ctrl key while dragging additional databases from the Schema Explorer to the query editor. To access those additional databases in your queries, use database.table notation, e.g., Northwind.Regions.Take(100). The databases that you query must reside on the same server.
The second approach is to list the extra database(s) that you want to query in the connection properties dialog. This dialog also lets you choose databases from linked servers. Here's how to proceed:
Add a new LINQ to SQL connection.
Choose Specify New or Existing Database and choose the primary database that you want to query.
Click the Include Additional Databases checkbox and pick the extra database(s) you want to include. You can also choose databases from linked servers in this dialog.
You can now do cross-database queries. These are properly optimized insofar as joins will occur on the server rather than the client.
Use linked servers with fully qualified names to query another database from the current DB. That should work.
using MainDatabase
go
insert Event_Type(code, description)
select distinct t1.code_id, t2.desc
from <Linked_Server>.OtherDatabase..codes t1
left join <Linked_Server>.OtherDatabase..lookup t2 on t1.key_id = t2.key_id and t2.category = 'Action 7'
where t2.desc is not null

How to make a select query for sql and access databases?

Using SQL server 2000 and Access 2003
Access Database Name - History.mdb
Access Table Name - Events
SQL Database Name - Star.mdf
SQL Table Name - Person
I want to take the field from person table, and include in Events table by using inner join
Tried Query
Select * from Events inner join person where events.id = person.id
So How to make a query for access and sql databases.
I want to make a Select query in access only. Not an sql Database.
Need Query Help?
While you can (possible, should -- why?) use a linked table, there are as ever more than one way to skin a cat. Here's another approach: put the connection details into the query test e.g. something like
SELECT *
FROM [ODBC;Driver={SQL Server};SERVER=MyServer;DATABASE=Star;UID=MyUsername;Pwd=MyPassword;].Person AS P1
INNER JOIN
[MS Access;DATABASE=C:\History;].[Events] AS E1
ON S1.seq = S2.seq
WHERE E1.id = P1.id;
You can set up a linked table in Access to your SQL Server, and the instructions on how to do so vary slightly in Access versions. Look in the help file for "Linked Table", or go here if you have Access 2007.
Once you have a linked table set up, you'll be able to access the SQL Server table in your query. Note that optimizing a linked table join takes some work.
You can create a linked table in Access, that points to the table in SQL. The rest you can achieve in the query designer.
You should add the msaccess db as a remote server.
then you can do that join

Resources