我在C#数据表中有一组ID。同时,我还有一个包含这些ID和一些其他数据的表。我的要求是删除包含数据表中指定的ID的记录(如果存在具有该ID的元组)。
我正在为此使用SqlDataAdapter。
SqlCommand command = new SqlCommand(text, con);
command.UpdatedRowSource = UpdateRowSource.None;
PrepareCommand(command, con, null, type, text, commandParas);
SqlDataAdapter adpt = new SqlDataAdapter();
adpt.DeleteCommand = command;
adpt.UpdateBatchSize = 2;
adpt.Update(dataTable);
connection.Close();
[我的意思是
- "text" is the name of the stored procedure containing the delete command. The argument given to this stored procedure is the ID ( picked from the list of IDs contained in the data table)
- "commandParas" is the argument passed to the stored procedure.
- "dataTable" contains the Ids used to delete the rows from SQL table. It contains only one column but several rows.
但是这不会导致表中删除指定的行。
EDIT
我在下面给出了存储过程
CREATE PROCEDURE someName(@ID INT)
AS
BEGIN
DELETE FROM SampleTable
WHERE id=@ID
END
下面给出的是创建数据表的代码
DataTable dt=new DataTable("abc");
dt.clear();
dt.Columns.Add(empId,typeof(int));
foreach(SomeClass t SomeList)
dt.Rows.Add(t.IdNo);
我犯错了吗?
我看到您呼叫PrepareCommand
,并将其设置为适配器的DeleteCmmand到适配器中,但是您在哪里运行命令?
正如DWright所指出的,您必须先将DataTable
中要删除的行设置为将其推送到SqlDataAdapter
批处理操作中。当我将行设置为已删除时,以下代码有效。
DataTable dt;
using (SqlConnection c = new SqlConnection(connectionString))
{
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM [dbo].[Dealer]", c))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
dt = ds.Tables[0];
}
}
dt.Rows[0].Delete();
dt.Rows[1].Delete();
dt.Rows[2].Delete();
using (SqlConnection c = new SqlConnection(connectionString))
{
var adapter = new SqlDataAdapter();
var command = new SqlCommand("DELETE FROM Dealer WHERE DealerId = @DealerId;", c);
var parameter = command.Parameters.Add("@DealerId", SqlDbType.Int, 3, "DealerId");
parameter.SourceVersion = DataRowVersion.Original;
adapter.DeleteCommand = command;
adapter.DeleteCommand.UpdatedRowSource = UpdateRowSource.None;
adapter.UpdateBatchSize = 2;
adapter.Update(dt);
}
以编程方式将行添加到表中后,调用AcceptChanges。