我必须将数据从一个 SQL Server 数据库复制到另一个 SQL Server 数据库。
在目标 SQL Server DB 中存在诸如 Identity 和其他数据类型之类的列,但在源数据库中不存在。源表只有 term 列,但目标表有 id(身份)和 term 列。
在复制期间,我收到如下错误:
当 IDENTITY_INSERT 设置为 ON 或复制用户插入 NOT FOR REPLICATION 标识列时,必须为表“Terms”中的标识列指定显式值。
string colNames = "";
foreach (DataColumn col in ds.Tables[0].Columns)
{
colNames += col.ColumnName + ",";
}
colNames = colNames.Remove(colNames.Length - 1, 1);
sqlCmd2.Parameters.Clear();
bool hasIdentityCol = false;
sqlCmd2.CommandType = CommandType.Text;
sqlCmd2.CommandText = "SELECT OBJECTPROPERTY(object_id('" + row["Table_Name"] + "'), 'TableHasIdentity')";
if (sqlCmd2.ExecuteScalar() != DBNull.Value && Convert.ToInt32(sqlCmd2.ExecuteScalar()) > 0)
{
hasIdentityCol = true;
}
if (hasIdentityCol == true)
{
sqlCmd2.CommandText = "SET IDENTITY_INSERT dbo." + row["Table_Name"] + " ON";
sqlCmd2.Transaction = sqlTran;
sqlCmd2.ExecuteNonQuery();
}
sqlCmd2.CommandText = "INSERT INTO " + txtDestinationDatabase.Text + ".dbo." + row["Table_Name"] + "(" + colNames + ") SELECT " + colNames + " FROM " + txtSourceDatabase.Text + ".dbo." + row["Table_Name"];
sqlCmd2.Transaction = sqlTran;
sqlCmd2.ExecuteNonQuery();
if (hasIdentityCol == true)
{
sqlCmd2.CommandText = "SET IDENTITY_INSERT " + txtDestinationDatabase.Text + ".dbo." + row["Table_Name"] + " OFF";
sqlCmd2.Transaction = sqlTran;
sqlCmd2.ExecuteNonQuery();
}