如何使用一个数据集更新两个表?

时间:2013-04-25 15:29:28

标签: c# sql save sql-update

我有一个数据集,其中包含来自两个SQL表的数据。

如何使用更新的数据集更新两个表? (因为加入不起作用)

             da = new SqlDataAdapter("select * from xxxx join.....", conn);
             builderForTable1 = new SqlCommandBuilder(da);
             da.Update(dataSetEmp, "Table");

3 个答案:

答案 0 :(得分:2)

如果您提供给数据适配器的查询返回多个结果集,则SQLDataAdapter.Fill()方法可以执行此操作。

var da = new SqlDataAdapter("select * from customers; select * from orders;", conn);
da.Fill(myDataset);

var customersDataTable = myDataset.Tables[0];
var ordersDataTable = myDataset.Tables[1];

然后,您可以根据需要添加自己的DataRelations。

myDataset.Relations.Add(new DataRelation(
    "CustomerOrders",
    customersDataTable.Columns["CustomerID"],
    ordersDataTable.Columns["CustomerID"]
)

答案 1 :(得分:0)

也许您可以使用交易?

SqlTransaction tr = conn.BeginTransaction();
    da = new SqlDataAdapter("select * from xxxx join.....", conn);
    builderForTable1 = new SqlCommandBuilder(da);
    da.Update(dataSetEmp, "Table");
    // ...
tr.Commit();

参考:

答案 2 :(得分:0)

Public Shared Function GetRecords(ByRef CNobj As System.Data.SqlClient.SqlConnection,
                                   ByRef RSobj As System.Data.DataSet,
                                   ByVal SQLquery As String,
                                   ByVal TableName() As String,
                                   Optional ByVal PrimKeys() As String = Nothing,
                                   Optional ByRef adapter As SqlDataAdapter = Nothing) As Integer

    On Error Resume Next
    Dim DataOkay As Integer = 0                             '[Set to negative if data bad]

    Dim suppliersAdapter As SqlDataAdapter = New SqlDataAdapter()

    'Create connection object, won't create if already exists
    If ConnectToDB(CNobj, False) = False Then
        'error creating object, Session("ErrorMsg") set by called code
        Return -1
    End If

    ' Open the connection.
    If CNobj.State = ConnectionState.Closed Then
        CNobj.Open()
    End If


    ' Create a SqlCommand to retrieve Suppliers data.
    Dim suppliersCommand As SqlCommand = New SqlCommand(SQLquery, CNobj)

    suppliersCommand.CommandType = CommandType.Text

    ' Set the SqlDataAdapter's SelectCommand.
    suppliersAdapter.SelectCommand = suppliersCommand


    ' Fill the DataSet.
    RSobj = New DataSet()
    suppliersAdapter.Fill(RSobj)
    If (Err.Number <> 0) Then
        DataOkay = -1
        _contexts.Session("ErrorMsg") = "Error reading records: " +
            DelDoubleQuotesInString(Err.Description)
        Call Err.Clear()
    ElseIf (RSobj.Tables.Count = 0) Then
        DataOkay = -2
        _contexts.Session("ErrorMsg") = "No tables read reading records for sql=" + SQLquery
    Else
        ' A table mapping names the DataTables.
        Dim IDX As Integer
        For IDX = 0 To TableName.Count - 1
            RSobj.Tables(IDX).TableName = TableName(IDX)
            If PrimKeys IsNot Nothing Then
                Dim primstr = PrimKeys(IDX)
                Dim primarr = Split(primstr, ",")
                Dim primcol(primarr.Count) As DataColumn
                Dim pidx As Integer
                For pidx = 0 To primarr.Count
                    primcol(pidx) = RSobj.Tables(IDX).Columns.Item(primarr(pidx))
                Next
                RSobj.Tables(IDX).PrimaryKey = primcol
            End If

        Next
        adapter = suppliersAdapter
    End If
    Return DataOkay
End Function

  Public Shared Function UpdateDB(ByRef dset As System.Data.DataSet, ByVal adapter As SqlDataAdapter)
    If dset.HasChanges = False Then
        Return True
    End If
    ' has multiple tables, select's separated by ;
    Dim SelectQry As String = adapter.SelectCommand.CommandText
    Dim commands() As String = Split(SelectQry, ";")
    Dim idx As Integer = 0

    For Each Table As System.Data.DataTable In dset.Tables
        'Connection object is global in shared ASP.NET module
        If CNobj.State = ConnectionState.Closed Then
            CNobj.Open()
        End If
        'Change select for table being updated.
        adapter.SelectCommand.CommandText = commands(idx)


        Dim cb As SqlCommandBuilder
        cb = New SqlCommandBuilder(adapter)

        adapter.InsertCommand = cb.GetInsertCommand(True)
        adapter.UpdateCommand = cb.GetUpdateCommand(True)
        adapter.DeleteCommand = cb.GetDeleteCommand(True)

        Try

            adapter.AcceptChangesDuringUpdate = True
            'force order delete, update, insert
            adapter.Update(Table.Select(Nothing, Nothing, DataViewRowState.Deleted))
            Table.AcceptChanges() 'Have to do after delete!
            adapter.Update(Table.Select(Nothing, Nothing, DataViewRowState.ModifiedCurrent))
            adapter.Update(Table.Select(Nothing, Nothing, DataViewRowState.Added))
        Catch
            HttpContext.Current.Session("ErrorMsg") = "Error saving data to DB: " + Err.Description
            adapter.SelectCommand.CommandText = SelectQry
            Return False
        End Try
        idx += 1
        cb.Dispose()
    Next
    'Put original select back for next call
    adapter.SelectCommand.CommandText = SelectQry
    Return True
End Function

我包括了我正在使用的两个例程。如果使用带分号的select调用,则第一个例程将获得多个表。我传入表名数组来分配给每个表。如果数据集将更新到服务器,那么我还传入主键并引用适配器以传递给更新调用。

我知道它是在VB而不是C#,但我转换为ASP.NET的Classic ASP已经在VB中了,我不想在它上面移植到C#。

更新代码为每个表的每个更新调用拆分选择字符串。

错误 - 上述代码不适用于所有表。对于一个表,如果我不接受更改它将不会更新 - 获得并发错误。在另一张表中,它表​​示在调用acceptchanges之前我有13个修改过的行 - 但是在调用之后它变为零,因此没有更新记录。我的猜测是,为一个获取并发错误的表生成的更新SQL是废话,并且不应该调用acceptchanges。我解决这个问题后会更新帖子。