兩張一樣的表對比其中一個表數據是否完整,不完整則從完整的表數據插入
#根據條件查詢到的表數據保存到DataTable中
private void Insert( DataTable dt1,DataTable dt2)
{
List<string> list1 = new List<string>();
List<string> list2 = new List<string>();
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 條件"