數據同步,可以用觸發器來實現

--====================================================
--發佈/訂閱的效果最好.  
--自己寫觸發器同步的實時性和可控制性最好.
--====================================================


--如果只是簡單的數據同步,可以用觸發器來實現.下面是例子:  
   
  --測試環境:SQL2000,遠程主機名:xz,用戶名:sa,密碼:無,數據庫名:test  
   
  --創建測試表,不能用標識列做主鍵,因爲不能進行正常更新  
  --在本機上創建測試表,遠程主機上也要做同樣的建表操作,只是不寫觸發器  
  if   exists   (select   *   from   dbo.sysobjects   where   id   =   object_id(N'[test]')  
  and   OBJECTPROPERTY(id,   N'IsUserTable')   =   1)  
  drop   table   [test]  
   
  create   table   test(id   int   not   null   constraint   PK_test   primary   key  
  ,name   varchar(10))  
  go  
   
  --創建同步的觸發器  
  create   trigger   t_test   on   test  
  for   insert,update,delete  
  as  
  set     XACT_ABORT   on  
  --啓動遠程服務器的MSDTC服務  
  exec   master..xp_cmdshell   'isql   /S"xz"   /U"sa"   /P""   /q"exec   master..xp_cmdshell   ''net   start   msdtc'',no_output"',no_output  
   
  --啓動本機的MSDTC服務  
  exec   master..xp_cmdshell   'net   start   msdtc',no_output  
   
  --進行分佈事務處理,如果表用標識列做主鍵,用下面的方法  
  BEGIN   DISTRIBUTED   TRANSACTION  
  delete   from   openrowset('sqloledb','xz';'sa';'',testdb.dbo.test)  
  where   id   in(select   id   from   deleted)  
  insert   into   openrowset('sqloledb','xz';'sa';'',testdb.dbo.test)  
  select   *   from   inserted  
  commit   tran  
  go  
   
  --插入數據測試  
  insert   into   test  
  select   1,'aa'  
  union   all   select   2,'bb'  
  union   all   select   3,'c'  
  union   all   select   4,'dd'  
  union   all   select   5,'ab'  
  union   all   select   6,'bc'  
  union   all   select   7,'ddd'  
   
  --刪除數據測試  
  delete   from   test   where   id   in(1,4,6)  
   
  --更新數據測試  
  update   test   set   name=name+'_123'   where   id   in(3,5)  
   
  --顯示測試的結果  
  select   *   from   test   a   full   join  
  openrowset('sqloledb','xz';'sa';'',test.dbo.test)   b   on   a.id=b.id  
   
 

發佈了4 篇原創文章 · 獲贊 8 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章