栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

SQLSever兩張數據表數據對比

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SQLSever兩張數據表數據對比

兩張一樣的表對比其中一個表數據是否完整,不完整則從完整的表數據插入

#根據條件查詢到的表數據保存到DataTable中
 private void Insert( DataTable dt1,DataTable dt2)
{
		List list1 = new List();
		List list2 = new List();
		int a = 0;
		//獲取要對比的字段名
		foreach (DataRow Row in dt1)
		 {
		   list1.Add(Row["字段名"].ToString());
		 }
		 //保存到數組中
		   String[] Array1 = list1.ToArray();

		   foreach (DataRow Row in dt2)
		{
		   list2.Add(Row["字段名"].ToString());
		}
		 
		  String[] Array2 = list2.ToArray();
		  
		  
		//對比數據不完整的表中是否包含數據完整表中的數據

		  for (int j = 0; j < Array1.Length; j++)
		{
			//如果有則繼續下一個循環
			if (Array2.Contains(Array1[j]))
		  {
			continue;
		  }
		  //沒有就插入數據
		 else
		 {
			string strsq1l = "insert into  [" + 數據表名 + "](字段,字段,字段......)";
			string strsql2 = "select newid() as 字段, 字段,......from [" + 數據表名 + "]  where 條件";
			string strsql = strsq1l + strsql2;
			//數據查詢
			a = hp.insert(strsql);
			if (a != 0)
		   {
			  MessageBox.Show("數據插入成功!", "提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
		   }
			else
		   {
			MessageBox.Show("數據插入失敗!", "提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
		   }
		   
		   }

		 }
}

1、假如A表存在

则 insert into A(a,b,c) (select a,b,c from B) 

2、假如A表不存在

select a,b,c into A from B 

3、假如需要跨数据库(在相同的服務器上)

insert into ADB.[dbo].A(a,b,c)  (select a,b,c from BDB.[dbo].B)

insert into  [" + 數據表名 + "](字段,字段,字段......)
select  字段, 字段,字段......from [" + 數據表名 + "]  where 條件"

其中插入一個固定值

insert into  [" + 數據表名 + "](字段,字段,字段......)
select  "固定值" as 字段, 字段,字段......from [" + 數據表名 + "]  where 條件"

insert into  [" + 數據表名 + "](字段,字段,字段....)

插入一個隨機的值

select newid() as 字段字段,字段......from [" + 數據表名 + "]  where 條件"

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/629892.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号