I am trying to write a database script (SQL Server 2008) that will copy information from database tables on one server to the corresponding tables in another database on another server.
I read that the correct way to do this is to use the sql statement in a format similar to the following:
INSERT INTO <linked_server>.<database>.<owner>.<table_name> SELECT * FROM <linked_server>.<database>.<owner>.<table_name>
Since multiple tables will be copied, I would like to declare variables at the top of the script to allow the user to specify the names of each server and database to be used. Then they can be used in all script. However, I'm not sure how to use the values ββof variables in actual SQL operations. I want to achieve something like the following:
DECLARE @SERVER_FROM AS NVARCHAR(50) = 'ServerFrom'
DECLARE @DATABASE_FROM AS NVARCHAR(50) = 'DatabaseTo'
DECLARE @SERVER_TO AS NVARCHAR(50) = 'ServerTo'
DECLARE @DATABASE_TO AS NVARCHAR(50) = 'DatabaseTo'
INSERT INTO @SERVER_TO.@DATABASE_TO.dbo.TableName SELECT * FROM @SERVER_FROM.@DATABASE_FROM.dbo.TableName
...
How to use @ variables in this code to make it work correctly?
, , , , NVARCHAR (50) - ?