title: How can i access multiple servers databases in loop in SQL server
body: <p>I am trying to access databases in loop which are in different different servers but i am getting error:</p>
  
  <blockquote>
    <p>"Msg 102, Level 15, State 1, Procedure SP_DATA_EXTRACTOR, Line 27 Incorrect syntax near '@DATABASE_NAME'."</p>
  </blockquote>
  
  <pre><code>IF OBJECT_ID('SP_DATA_EXTRACTOR') IS NOT NULL DROP PROCEDURE SP_DATA_EXTRACTOR 
  GO CREATE PROCEDURE [DBO].SP_DATA_EXTRACTOR AS 
  DECLARE @UNIT_ID INT;
  DECLARE @SERVER_NAME VARCHAR(100);
  DECLARE @DATABASE_NAME VARCHAR(100);
  BEGIN
     DECLARE DATACURSOR CURSOR FOR 
     SELECT
        UNIT_ID,
        SERVER_NAME,
        DATABASE_NAME 
     FROM
        UNIT_MASTER 
     WHERE
        STATUS = 'A';
  OPEN DATACURSOR;
  FETCH NEXT 
     FROM
        DATACURSOR INTO @UNIT_ID,
        @SERVER_NAME,
        @DATABASE_NAME;
  WHILE @@FETCH_STATUS = 0 
  BEGIN
     DELETE
        VW_REFUNDS_TABLE 
     WHERE
        UNIT_ID = @UNIT_ID 
        AND CONVERT(DATE, DATECREATED, 103) = CONVERT(DATE, GETDATE(), 103);
  INSERT INTO
     VW_REFUNDS_TABLE(UNIT_ID, TICKETTOTAL, DATECREATED, REFUNDDATE, DEBITAMOUNT, CREDITAMOUNT, TERMINALID, CASHIER, TERMINAL, REFUNDMINS, MANAGER, USERID, ID) 
     SELECT
        @UNIT_ID,
        TICKETTOTAL,
        CONVERT(SMALLDATETIME, DATECREATED, 103) DATECREATED,
        CONVERT(SMALLDATETIME, REFUNDDATE, 103) REFUNDDATE,
        DEBITAMOUNT,
        CREDITAMOUNT,
        TERMINALID,
        CASHIER,
        TERMINAL,
        REFUNDMINS,
        MANAGER,
        USERID,
        ID 
     FROM
        @SERVER_NAME.@DATABASE_NAME.dbo.VW_REFUNDS 
     WHERE
        CONVERT(DATE, DATECREATED, 103) = CONVERT(DATE, GETDATE(), 103);
  FETCH NEXT 
     FROM
        DATACURSOR INTO @UNIT_ID,
        @SERVER_NAME,
        @DATABASE_NAME;
  END;
  CLOSE DATACURSOR;
  DEALLOCATE DATACURSOR;
  END;
  </code></pre>