ASP.NET使用MergeInto做数据同步,同步SQLSERVER不同数据库的相同表结构的数据

 

        public string SynchronousData()
        {
            ReturnJson Rejson = new ReturnJson();
       //将WebConfig中的数据库连接name中的值写进来
            string connS = ConfigurationManager.ConnectionStrings["name"].ConnectionString;
       
using (SqlConnection conn = new SqlConnection(connectionSub)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { try { cmd.CommandText = "存储过程名"; cmd.CommandType = CommandType.StoredProcedure; var ReExcute = cmd.ExecuteNonQuery(); if (ReExcute >= 0) { conn.Close(); Rejson.Code = "1"; Rejson.Errmsg = "同步成功"; return ToJson(Rejson); } else { conn.Close(); Rejson.Code = "0"; Rejson.Errmsg = "同步失败"; return ToJson(Rejson); } } catch { conn.Close(); Rejson.Code = "3"; Rejson.Errmsg = "未知异常"; return ToJson(Rejson); } } } }

 

存储过程

Create PROCEDURE [存储过程名]
AS
BEGIN
MERGE INTO 目标数据表名 as T
USING 源数据表名 as S
ON T.[Id] = S.[Id]
WHEN MATCHED
THEN UPDATE SET T.[Name]=S.[Name]
WHEN NOT MATCHED
THEN INSERT VALUES(S.[Name])
WHEN NOT MATCHED BY SOURCE
THEN DELETE;
END

 

posted on 2017-03-14 13:25  阿门668  阅读(1124)  评论(0编辑  收藏  举报

导航