Using T-Sql, how can I insert from one table on a remote server into another table on my local server? - sql

Given the remote server 'Production' (currently accessible via an IP) and the local database 'Development', how can I run an INSERT into 'Development' from 'Production' using T-SQL?
I'm using MS SQL 2005 and the table structures are a lot different between the two databases hence the need for me to manually write some migration scripts.
UPDATE:
T-SQL really isn't my bag. I've tried the following (not knowing what I'm doing):
EXEC sp_addlinkedserver
#server = N'20.0.0.1\SQLEXPRESS',
#srvproduct=N'SQL Server' ;
GO
EXEC sp_addlinkedsrvlogin '20.0.0.1\SQLEXPRESS', 'false',
'Domain\Administrator', 'sa', 'saPassword'
SELECT * FROM [20.0.0.1\SQLEXPRESS].[DatabaseName].[dbo].[Table]
And I get the error:
Login failed for user ''. The user is
not associated with a trusted SQL
Server connection.

create a linked server and then use 4 part notation
insert table
select <column names>
from LinkedserverName.DatabaseName.SchemaName.TableName
you can also use OPENROWSET
example
insert table
SELECT a.*
FROM OPENROWSET('SQLNCLI', 'Server=Seattle1;Trusted_Connection=yes;',
'SELECT GroupName, Name, DepartmentID
FROM AdventureWorks2008R2.HumanResources.Department
ORDER BY GroupName, Name') AS a;
try this to create the login
EXEC master.dbo.sp_addlinkedsrvlogin #rmtsrvname=N'20.0.0.1\SQLEXPRESS',
#useself=N'False',
#locallogin=NULL,
#rmtuser=N'sa',
#rmtpassword='saPassword'

You can define the PROD Server as Linked Server to the DEV box and then access it.
However I think it would be easier to get a backup from PROD Box and Restore it to DEV or use SSIS for Schema Import.

Look into the RedGate tools, esp. SQL Data Compare. If that's not an option you should look at OPENDATASOURCE or OPENROWSET to access the remote database.

Well you can use a linked server and then use the 4 part names for objects (See BOL for how to set up a linked server)
Or you could use SSIS to set up the data migrations and connect to the remote server
Or you could use OPENROWSET
I'd probably use SSIS, but I'm already familiar with it.

Use SSMS. Right click on the target DB and select "Tasks", "Import Data". You will be able to preview the data and make conversions visually. Save the package in SSIS or run it now.

Related

How to insert data from prod server to dev server in SQL Server

I would like to insert data from prod server to dev server for a particular table.
I am using insert into SQL query and fully qualified name. That is I am specifying server name, databsename, schema name and table name.
insert into ServerADev.[ING_DB].dbo.[Table1]
select *
from ServerAProd.[ING_DB].dbo.[Table1]
where ID = '08914'
ID is the column in Table1.
For above query I am getting an error:
Cannot find ServerAProd in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers.
When I EXEC sp_addlinkedserver #server='ServerAProd', I am getting:
User does not have permission to perform this action.
Do I need to make a request to DBA (database admin) to grant permission to perform this query?
You need to set up a linked server to query a foreign server.
So, either:
ServerAProd is not what you named the linked server
or
You didn't create a linked server yet. You can use the sp_addlinkedserver from the error message, or browse to "server objects" in the object explorer then right-click -> new on "Linked Servers". See the link above for more details.
For your edit... yes this requires permissions:
When using Transact-SQL statements, requires ALTER ANY LINKED SERVER permission on the server or membership in the setupadmin fixed server role. When using Management Studio requires CONTROL SERVER permission or membership in the sysadmin fixed server role.
1. create linked server for the dev server on production server,
2. use this openquery() to insert data, so that you can insert large data very quickly.
INSERT OPENQUERY (devservername, 'SELECT * FROM devservar_database..dev_server_table_name')
select * from production_table_database_name..production_table_table_name

How to transfer one table from server 1 to the table in server 2?

Suppose I have two database on two separate servers:
server1:
ip 127.0.0.1
user1, passwd1
db1.tbl1
server2:
ip 127.0.0.2
user2, passwd2
db2.tbl2
Suppose tb1 and tb2 has the same table structure. I've search the web, people suggest to set up linked-servers, but I don't want to set up.
Since I know the password and ip address, things should go very easy like this:
insert into db2.tbl2
select *
from db1.tbl1
However I don't know where to put the ip address and username and password.
Try this (run it on server1):
INSERT INTO [db1].[tbl1]
SELECT * FROM OPENDATASOURCE(
'SQLOLEDB',
'Data Source=127.0.0.2;Initial Catalog=db2;Persist Security Info=True;User ID=user2;Password=passwd2'
).db2.tbl2
You can refer to this article.
You tagged your question with many RDBMS.
My answer is about SQL Server.
Since I know the password and ip address, things should go very easy
like this: insert into db2.tbl2 select * from db1.tbl1
And this is exactly the syntax you can use in case of linked servers. You incapsulate connection string in the definition of linked server, then the only thing that changes is linked server name in your code:
insert into db2.tbl2 select * from server1.db1.tbl1
example of linked server setup:
EXEC master.dbo.sp_addlinkedserver #server = N's_2005', #srvproduct=N'', #provider=N'SQLNCLI', #datasrc=N'127.0.0.1,8851'
go
EXEC master.dbo.sp_addlinkedsrvlogin #rmtsrvname=N's_2005',#useself=N'False',#locallogin=NULL,#rmtuser=N'login1',#rmtpassword='*****'
go
select top 5 * from [s_2005].[Northwind].[dbo].[Employees]
If you want other solutions, you can use OPENROWSET (Transact-SQL)
providing the whole connection string in your INSERT every time you want to access remote server:
select a.* from openrowset('SQLNCLI', 'Server=127.0.0.1,8851;Trusted_Connection=no;uid=login1;pwd=*****;', 'select top 5 * from [Northwind].[dbo].[Employees]') as a
The third option is SSIS where you incapsulate connection strings into SourceConnection and DestinationConnection
Here is a picture of the same result using linked server and openrowset:
If you are using SQL Server Management Studio then there is a wizard to import/export data between servers and databases:
https://learn.microsoft.com/en-us/sql/integration-services/import-export-data/start-the-sql-server-import-and-export-wizard?view=sql-server-2017

I need to add a linked server to a MS Azure SQL Server

I have tried and tried, and can not get linked. I can connect to the server using SSMS, but can not link to it from a local server. Here is my script (replacing things in brackets with pertainent information):
EXEC master.dbo.sp_addlinkedserver
#server = N'[servername].database.windows.net',
#srvproduct = N'Any',
#provider = N'MSDASQL',
#datasrc = N'Azure_ODBC1'
GO
EXEC master.dbo.sp_addlinkedsrvlogin
#rmtsrvname = N'[servername]',
#useself = N'False',
#locallogin = NULL,
#rmtuser = N'[username]',
#rmtpassword = '[password]'
GO
As specified in ckarst second link, there is a solution that works. I am posting it here to save you the trouble to search for it. As suggested by JuanPableJofre in this page Azure feedback :
Using SQL 2014, I was able to do a distributed query between a local SQL server and a SQL Azure.
First, I created a Linked-Server:
Linked Server (name): LinkedServerName
Provider: Microsoft OLE DB Provider for SQL Server
Product name: (blank)
Data Source: azure-db.database.windows.net
Provider string: (blank)
Location: (blank)
Catalog: db-name
In security options: (*)
Be made using this security context
Remote login: azure-user-name
With password: yourPassword
In SSMS entered the following test query:
use [Local_DB]
go
Select *
from [LinkedServerName].[RemoteDB].[dbo].[Remote_Table]
It worked beautifully !!
To summarize, the linked server is created on your local database. The catalog (database name) is important as Azure might not let you specify it in a query (ie: use azureDBName will not work on Azure), so the database name has to be in the catalog.
Unfortunately, Linked Server is not supported by SQL Azure DB.
https://msdn.microsoft.com/en-us/library/azure/ee336281.aspx
However, as you can see from the forum link below, Microsoft is aware of the scenario and the customer feedback has been heard. http://feedback.azure.com/forums/217321-sql-database/suggestions/402636-cross-database-reference
While Azure DB doesn't support defining Linked Servers, you can use the recently previewed Elastic Query feature to define an "External Data Source" that is just another Azure DB database, and define "External Tables" that are references to tables in that external database. Then you can query these as though they are local objects. This is very similar to the Linked Server concept and is described in detail here.
-- Make a link to the cloud
EXEC sp_addlinkedserver
#server='[servername].database.windows.net', -- specify the name of the linked server
#srvproduct=N'Azure SQL Db',
#provider=N'SQLNCLI',
#datasrc='yourservername', -- add here your server name
#catalog='FCS';
GO
--Set up login mapping
EXEC sp_addlinkedsrvlogin
#rmtsrvname = '[servername].database.windows.net',
#useself = 'FALSE',
#locallogin=NULL,
#rmtuser = 'username',
#rmtpassword = 'password'
GO
This does create a linked server in my envirnoment, however it doesn't connect to the catalog that I have specified (FCS). It connects to a default for some reason. Is there something i am doing wrong

Transfer a table from a server to another server

Besides from Import and Export Wizard, Is there any query to transfer a table from a server to another server in SQL Server 2008?
SELECT * INTO [Server1].[db_name].[dbo].[table_name]
FROM [Server2].[db_name].[dbo].[table_name]
There are several options. If you have the correct permissions, you can create a Linked Server following instructions here: http://msdn.microsoft.com/en-us/library/ff772782.aspx
and then use OPENQUERY (http://msdn.microsoft.com/en-us/library/ms188427.aspx) to select the records:
SELECT * INTO new_db.new_schema.new_table
FROM OPENQUERY(linked_server_name, 'select * from old_db.old_schema.old_table');
Or you can do something similar with OPENROWSET (http://technet.microsoft.com/en-us/library/ms190312.aspx) if you don't want to go through setting up the linked server:
SELECT * INTO new_db.new_schema.new_table
FROM OPENROWSET('SQLNCLI', 'Server=OldServer;Trusted_Connection=yes;',
'select * from old_db.old_schema.old_table');
Both may require some tweaking based on the authentication method you're using, usernames, privileges, and all that.
Assuming you can log into Server1, and have a linked server setup for Server2, another option is OPENQUERY.
SELECT *
INTO [db_name].[dbo].[table_name]
FROM OPENQUERY([Server2], 'select * from [db_name].[dbo].[table_name]')
Keep in mind, this will not copy indexes/statistics. Those would need to be scripted and re-created.
If you need to keep them in sync, then I would look into SQL Replication.
You can define a linked server to server2 inside server1, then run the query in server1:
SELECT * INTO [db_name].[dbo].[table_name]
FROM [Server2].[db_name].[dbo].[table_name]
More about linked servers:
http://msdn.microsoft.com/en-us/library/ms188279.aspx
Assuming both server1 and server2 are sql server then You do not need a openquery. Create a linked server on server1 for server2 and write query
select * into server1.schema.table_name
from server2.schema.table_name

Calling sp_help on linked server

I have a table named 'Application' on linked server (hosting server) in schema 'ID'.
I am trying to view the details of same using sp_help.
But I'm not able to do it.
The problem is:
1. sp_help is in schema dbo. (It is obvious!)
2. But my table in another schema named ID. (e.g. select * from ID.Application)
I've added linked server to my local sql server management studio.
And tried:
exec [198.198.198.198].[sms].[dbo].sp_help applicantion
exec [198.198.198.198].[sms].[dbo].sp_help id.applicantion
exec [198.198.198.198].[sms].[dbo].sp_help sms.id.applicantion
'sms' is my database on linked server.
Results: syntax error.
I tried: SQL using sp_HelpText to view a stored procedure on a linked server
But my problem is 2 different schema.
Any suggestions??
Does this work?
exec [198.198.198.198].[sms].[dbo].sp_help 'id.applicantion'