How can I get data from 2 different SQL Servers - sql-server

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

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!

Is it possible to connect an Access form to a SQL Server view

I'm migrating an Access DB to SQL Server and everything is slowly coming along but Im not sure how to connect the Access forms to the SQL Server views.
So far I have all the tables linked to SQL Server and Im working on migrating the Access queries into views, but Ive got this error, A2SS0069: External variable cannot be converted
which references a form in my Access file:
SELECT TOP 9223372036854775807 WITH TIES
[AcuteHospitals].[NHSN_ID],
[AcuteHospitals].[HospitalName],
[Location_LOV].[Description] AS Location,
Sum([RateTable_CLABData].[clabcount]) AS [Number of CLABSI],
Sum([RateTable_CLABData].[numcldays]) AS [Central Line Days],
[RateTable_CLABData].[CLAB_Mean] AS [National Average]
FROM
(([AcuteHospitals]
LEFT JOIN [RateTable_CLABData]
ON [AcuteHospitals].[NHSN_ID] = [RateTable_CLABData].[orgID])
LEFT JOIN [Location_LOV]
ON [RateTable_CLABData].[loccdc] = [Location_LOV].[CDCLoc])
LEFT JOIN [SummaryYQ_LOV]
ON [RateTable_CLABData].[summaryYQ] = [SummaryYQ_LOV].[StartDate]
WHERE ((([SummaryYQ_LOV].[SummaryYQ]) = forms!YQ_Location.text5 ))
GROUP BY
[AcuteHospitals].[NHSN_ID],
[AcuteHospitals].[HospitalName],
[Location_LOV].[Description],
[RateTable_CLABData].[CLAB_Mean],
[RateTable_CLABData].[loccdc]
HAVING ((([RateTable_CLABData].[loccdc]) NOT LIKE '%ped%'))
ORDER BY [AcuteHospitals].[HospitalName], [RateTable_CLABData].[loccdc]
Its the line WHERE ((([SummaryYQ_LOV].[SummaryYQ]) = forms!YQ_Location.text5 ))
So I need to know if it's possible and how to get this new view to connect with the Access form.
The problem is here
WHERE ((([SummaryYQ_LOV].[SummaryYQ]) = forms!YQ_Location.text5 ))
You cannot convert such Access query into a SQL View, but you can use Stored Procedure instead and pass value from the field forms!YQ_Location.text5 as parameter.
Also, you don't need this TOP 9223372036854775807 WITH TIES it is redundant.
You can't reference the Access form in a SQL View directly. You will need to rethink the logic in this. You could either create a number of Views with the appropriate values hard-coded (inadvisable) or convert the View to a Stored Procedure and pass the value in as a parameter.
For example (assuming the parameter is a string):
create proc s_MyStoredProc
#Location varchar(50)
AS
BEGIN
SELECT
[AcuteHospitals].[NHSN_ID],
[AcuteHospitals].[HospitalName],
[Location_LOV].[Description] AS Location,
Sum([RateTable_CLABData].[clabcount]) AS [Number of CLABSI],
Sum([RateTable_CLABData].[numcldays]) AS [Central Line Days],
[RateTable_CLABData].[CLAB_Mean] AS [National Average]
FROM
(([AcuteHospitals]
LEFT JOIN [RateTable_CLABData]
ON [AcuteHospitals].[NHSN_ID] = [RateTable_CLABData].[orgID])
LEFT JOIN [Location_LOV]
ON [RateTable_CLABData].[loccdc] = [Location_LOV].[CDCLoc])
LEFT JOIN [SummaryYQ_LOV]
ON [RateTable_CLABData].[summaryYQ] = [SummaryYQ_LOV].[StartDate]
WHERE ((([SummaryYQ_LOV].[SummaryYQ]) = #Location ))
GROUP BY
[AcuteHospitals].[NHSN_ID],
[AcuteHospitals].[HospitalName],
[Location_LOV].[Description],
[RateTable_CLABData].[CLAB_Mean],
[RateTable_CLABData].[loccdc]
HAVING ((([RateTable_CLABData].[loccdc]) NOT LIKE '%ped%'))
ORDER BY [AcuteHospitals].[HospitalName], [RateTable_CLABData].[loccdc]
END
Just create the SQL server view, and then from the Access font end link to that view. It is easy, not much work.
As for any parameters? Just remove them from the query and views. You then just open up the report using a where clause from the Access client.
In fact using a Access form or report that is bound to a linked table (or in this case view) is easy, and Access will ONLY pull down the reocrds you specifiy in the "where" clause of the open form or open report command.
SQL Server has an excellent (and free) MS-Access to MS-SQL migration tool. It does a very good job of converting MS-Access queries. I haven't tried converting queries with form parameters, but it is certainly worth a look and you may learn some things as well, especially if you plan to convert other queries. http://www.microsoft.com/sqlserver/en/us/product-info/migration-tool.aspx#oracle.

Update database table from one SQL Server database table to another?

I am trying to update database fields from one SQL Server table to another.
Our production SQL Server is [spdbprod.test.com\spprod], our QA server is [spdbQA.test.com\spQA].
I need to update table in production from QA table. I using this SQL statement but, it is giving an error.
UPDATE
[spdbprod.test.com\spprod].[aspnetdb].[dbo].[Communities_Groups] as t1
SET
t1.Show = (Select t2.show from [spdbQA.test.com\spQA].[aspnetdb].[dbo].
[Communities_Groups] as t2 where t1.GroupID = t2.GroupdID)
What I am missing here?
Error:
UPDATE. ("Incorrect syntax near the keyword 'as'.")
You are using table alias in a wrong way. You cannot do UPDATE table1 t SET field1=val, you have to write UPDATE table1 SET field=val (Or UPDATE table1 SET field=val FROM table1 t). So change your query to
UPDATE [spdbprod.test.com\spprod].[aspnetdb].[dbo].[Communities_Groups]
SET Show = t2.show
FROM [spdbprod.test.com\spprod].[aspnetdb].[dbo].[Communities_Groups] t1
INNER JOIN [spdbQA.test.com\spQA].[aspnetdb].[dbo].
[Communities_Groups] t2 ON (t1.GroupID = t2.GroupID)
I know this has been answered already but this worked for me.
Add a Linked Server under Server Objects | Linked Servers:
Microsoft documentation.
Name the Linked Server [SERVER-NAME or <some ipaddress>, <some-port>]
e.g. [10.0.0.200,2345] - I am using port 2345 but the standard MS SQL port is 1433.
Example:
We have a [Customers] table
We want to update [CustomerAddress]-field for CustomerId = 123
We want to use backup data from a server called [backupServer]
The [backupServer] is the machine where we execute the SQL
This is the SQL-code:
UPDATE production
SET
CustomerAddress = backupServer.CustomerAddress
FROM
[10.0.0.200,2345].[ProductionDatabase].[dbo].[Customers] production
INNER JOIN
[BackupDatabase].[dbo].[Customers] backupServer
ON
production.CustomerId = backupServer.CustomerId
WHERE
backupServer.CustomerId = 123
Generalized format:
UPDATE production
SET
columnName = backupServer.columnName
FROM
[SERVER-NAME or IP,PORT].[ProductionDatabase].[dbo].[tableName] production
INNER JOIN
[BackupDatabase].[dbo].[tableName] backupServer
ON
production.SomeId = backupServer.SomeId
WHERE
backupServer.SomeId = <id>
I believe you have to have a database link (linked servers) for this to work.
I do not have access to two SQL servers here at work so I cannot test it, but I sure that you need the link.
Do you have a linked server setup?
Here is a URL that may help
http://msdn.microsoft.com/en-us/library/ms188279.aspx
You need to add a Linked Server under Server Objects
You can name that Linked Server either with "CHOOSEN-NAME" or
[ipaddress , port number]
how to add a linked server using tsql , please check this link : how to find linked server
for an example purpose suppose i have named the linked server
"DESTINATION_SERVER" , database name is "DESTINATION_DB" and table
name is "DESTINATION_TBL". then from your source server your query could be like this below:
UPDATE t1
SET t1.updatecolumn = t2.updatecolumn
FROM [DESTINATION_SERVER].[DESTINATION_DB].[dbo].[DESTINATION_TBL] t1
INNER JOIN [SOURCE-SERVER].[SOURCE_DB].[dbo].
[SOURCE_TBL] t2 ON (t1.matcingcolumn = t2.matchingcolumn)

Query with Two Different 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"

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