sql笨办法同步数据

时间:2021-01-27 15:15:35
Helpers.SqlHelper sqlHelper = new Helpers.SqlHelper("server=***;database=Cms;user id=sa;password=123");

            string[] tableNames = { "A", "B", "C", "D", "E" };
var sb = new StringBuilder();
foreach (var tableName in tableNames)
{
var dt = sqlHelper.ExecuteDataTable("select * from "+tableName+" where 0=0"); sb.AppendLine("set identity_insert "+tableName+" on");
sb.AppendLine("truncate table " + tableName + " ");
if (dt != null)
{
var val = string.Empty; for (int i = ; i < dt.Rows.Count; i++)
{
if (i% == )
{
sb.AppendLine("insert into [" + tableName + "](");
for (int r = ; r< dt.Columns.Count; r++)
{
if (r > )
sb.Append(",");
sb.Append(dt.Columns[r].ColumnName);
}
sb.Append(")");
sb.AppendLine("values");
}
else
sb.AppendLine(","); sb.Append("(");
for (int j = ; j < dt.Columns.Count; j++)
{
if (j > )
sb.Append(","); val = dt.Rows[i][j].ToString();
if (dt.Columns[j].DataType == typeof (DateTime) || dt.Columns[j].DataType == typeof (int) ||
dt.Columns[j].DataType == typeof (long))
{
if (string.IsNullOrEmpty(val))
{
sb.Append("null");
}
else
{
sb.Append("'" + val + "'");
}
}
else
{
sb.Append("'" + val.Replace("'", "''") + "'");
}
}
sb.Append(")");
}
}
sb.AppendLine();
sb.AppendLine("set identity_insert " + tableName + " off");
sb.AppendLine();
}
var sql = sb.ToString(); Console.Write(sql);
Console.Read();

identity表导入失败,所以就用了这种笨办法来同步数据