如何在SQL服务器中循环访问多个服务器数据库

时间:2017-10-07 22:08:59

标签: sql-server stored-procedures

我正在尝试访问不同服务器中的循环数据库但我收到错误:

  

"消息102,级别15,状态1,过程SP_DATA_EXTRACTOR,第27行' @ DATABASE_NAME附近的语法不正确'。"

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;

0 个答案:

没有答案