在向表中添加或更新记录之前,我正在尝试删除所有表中存在的列。由于 Azure 的某些功能以及在移动设备上同步表,这是必要的。在下面的示例中,我将删除名为“Col4”。
到目前为止,以下是我最好的方法。在使用 清理 SQL 命令后,它会进行简单的字符串替换SqlCommandBuilder
(请参阅代码下方的清理后的 SQL 示例)。使用字符串替换删除列后,我替换SqlCommandBuilder
. 我希望使用字符串生成器作为删除列的一种方式,因为与commandText
参数相比,格式应该是一致的,参数可能会有很大差异。但是我担心这种方法充满了问题,例如我可能还需要修改更新后的 SQL 命令中的 VALUES 部分,但这可能很困难,因为我正在处理具有不同列数的不同表. 无论如何,如您所见,我在代码中指示的位置出现错误。
有没有更简单的方法来删除 da.InsertCommand = \command 之前没有指定值的列
public bool UpdateTest(DataTable dt, string commandText)
{
bool success = false;
SqlDataAdapter da = null;
SqlCommand command = null;
SqlCommandBuilder cb = null;
try
{
lock ((_Lock))
{
using (SqlConnection connX = new SqlConnection(_ConnectionString))
{
connX.Open();
command = new SqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = commandText;
command.Connection = connX;
da = new SqlDataAdapter();
da.SelectCommand = command;
// This section is where I try to remove the column
SqlCommandBuilder testcb = new SqlCommandBuilder(da);
string testSQL = testcb.GetInsertCommand.CommandText;
testSQL = testSQL.Replace(", [Col4]", string.Empty);
da.SelectCommand.CommandText = testSQL;
cb = new SqlCommandBuilder(da);
da.InsertCommand = cb.GetInsertCommand; //Code fails here--not surprising
da.DeleteCommand = cb.GetDeleteCommand;
da.UpdateCommand = cb.GetUpdateCommand;
da.Update(dt.GetChanges);
success = true;
}
}
}
catch (Exception ex)
{
}
finally
{
dt = null;
if (!command == null)
{
command.Dispose();
command = null;
}
if (!(da == null))
{
da.Dispose();
da = null;
}
}
return success;
}
原文da.SelectCommand.CommandText
:
"INSERT INTO [Table] ([Col1], [Col2], [Col3], [Col4]) VALUES (@p1, @p2, @p3, @p4)"
更新da.SelectCommand.CommandText
:
"INSERT INTO [Table] ([Col1], [Col2], [Col3]) VALUES (@p1, @p2, @p3, @p4)"