在VB.Net中动态更新SQL Server数据库

时间:2011-09-19 10:06:06

标签: sql-server vb.net

我正在尝试使用“预订”表单中的文本框值动态生成查询,以仅更新用户输入的值。

我使用以下代码:

Dim str As String

str = "UPDATE Bookings SET "
Dim first As Integer = 1
For Each x As Control In Me.Controls
    If x.GetType Is GetType(TextBox) Then
        If first = 1 Then
            first = 2
        Else
            str &= ","
        End If
        If x.Tag = 1 Then
            str = str & x.Name & " = @" & x.Name
        End If
    End If
Next

但它正在生成如下查询:

Update Bookings SET ,,booking_date = @booking_date,,,,,cust_name = @cust_name where bookingID = @bookingID

或者,如果我只想更新1个字段,则会生成以下内容:

Update Bookings SET ,,,,,,,cust_name = @cust_name where bookingID = @bookingID

1 个答案:

答案 0 :(得分:1)

Dim str As String  
str = "UPDATE Bookings SET "
Dim comma As string = ""
For Each x As Control In Me.Controls
  If x.GetType Is GetType(TextBox) Then
    If x.Tag = 1 Then
      str &= comma & x.Name & " = @" & x.Name
      comma = ","
    End If
  End If
Next

这是一线答案。

Dim str = "UPDATE Bookings SET " & String.Join(",", (From _E In Controls.OfType(Of Control)() Where _E.GetType() Is GetType(TextBox) AndAlso _E.Tag = "1" Select _E.Name).ToList())