title: How to select data from another sql server server tables in sql script?
body: <p>I want to know how to query data from another SQL Server instances' tables in SQL script.</p>
  
  <p>I am writing sql script running on <code>127.0.0.1\SQLINSTANCE1</code> but inside the script there is going to select data from <code>127.0.0.2\SQLINSTANCE2</code> then return the result data as part of calculation.</p>
  
  <p>After googled, there seems uses the <code>sp_addlinkedserver</code> and <code>sp_addlinkedsrvlogin</code> stored procedures for doing that, but unfortunately there is no complete sample working.</p>
  
  <p>I have some work here but not working as expected. For example, when it was executed once more then there would pop up some error like the server already linked. But how I can execute this script for linking the server and then abandoning it?</p>
  
  <pre><code>DECLARE @remoteserver VARCHAR = '127.0.0.2\SQLINSTANCE2';
  
  EXEC master.sys.sp_addlinkedserver  @server = @remoteserver
                                  ,   @srvproduct = 'SQL Server';
  
  EXEC master.sys.sp_addlinkedsrvlogin    @rmtsrvname = @remoteserver
                                      ,   @useself = 'false'
                                      ,   @locallogin = NULL
                                      ,   @rmtuser = 'sa'
                                      ,   @rmtpassword = 'password';
  </code></pre>
  
  <p>To the other side, how can I create an alias for this ugly remoteserver name?
  I rather to use some elegant name like RS in <code>select * from [RS].[db].[dbo].[table]</code></p>