如果它不存在,如何使SQL跳过记录? VB.net

时间:2013-12-18 22:09:24

标签: sql vb.net sqlite loops

我有一个循环,它将遍历所有唯一ID以查找现有记录。如果在循环中有一个带有该数字的ID,那么我希望它做某事,否则我希望它跳到下一个数字。我有一个柜台,所以我可以做那个部分。我遇到的问题是,当它没有遇到ID时,它会在尝试将任何内容放入有意义的变量时出错。如果数字不存在,我如何才能进入下一个数字。箭头出现错误。我的代码如下:

Sub Cmd_CalculateClick(sender As Object, e As EventArgs)
    weekcount = 0

    'Calculate Bills for whole term
    Do Until counter = 9999
        valid_user = 0
        SQLcommand = SQLconnect.CreateCommand
        'Create SQL statement
        SQLcommand.CommandText = "SELECT Pupil_ID FROM Pupil WHERE Pupil_ID = '" & counter & "' AND Waiting_List = 'F' "
        'Extract data
        SQLreader = SQLcommand.ExecuteReader()


---->   valid_user = SQLreader("Pupil_ID")



        'Clear SQL command buffer
        SQLcommand.Dispose()

        If valid_user = 0 Then
            counter = counter + 1
        Else If valid_user > 0 Then
            'Fetch Pupil attendance Days
            SQLcommand = SQLconnect.CreateCommand
            'Create SQL statement
            SQLcommand.CommandText = "SELECT Attendance_Monday, Attendance_Tuesday, Attendance_Wednesday, Attendance_Thursday, Attendance_Friday FROM Pupil WHERE Pupil_ID = '" & valid_user & "'"
            'Extract data
            SQLreader = SQLcommand.ExecuteReader()

            If SQLreader("Attendance_Monday") = "T" Then
                Monday = True
                weekcount = weekcount + 1
            Else
                Monday = False
            End If

            If SQLreader("Attendance_Tuesday") = "T" Then
                Tuesday = True
                weekcount = weekcount + 1
            Else
                Tuesday = False
            End If

            If SQLreader("Attendance_Wednesday") = "T" Then
                Wednesday = True
                weekcount = weekcount + 1
            Else
                Wednesday = False
            End If

            If SQLreader("Attendance_Thursday") = "T" Then
                Thursday = True
                weekcount = weekcount + 1
            Else
                Thursday = False
            End If

            If SQLreader("Attendance_Friday") = "T" Then
                Friday = True
                weekcount = weekcount + 1
            Else
                Friday = False
            End If

            'Clear SQL command buffer
            SQLcommand.Dispose()

            'Fetch Total Sessions for that half term
            SQLcommand = SQLconnect.CreateCommand
            'Create SQL statement
            SQLcommand.CommandText = "SELECT Session_Monday, Session_Tuesday, Session_Wednesday, Session_Thursday, Session_Friday FROM Session"
            'Extract data
            SQLreader = SQLcommand.ExecuteReader()

            sesmon = SQLreader("Session_Monday")
            sestue = SQLreader("Session_Tuesday")
            sesmon = SQLreader("Session_Wednesday")
            sesmon = SQLreader("Session_Thursday")
            sesmon = SQLreader("Session_Friday")

            'Clear SQL command buffer
            SQLcommand.Dispose()

            'Fetch Cost for each session
            SQLcommand = SQLconnect.CreateCommand
            'Create SQL statement
            SQLcommand.CommandText = "SELECT Price_Monday, Price_Tuesday, Price_Wednesday, Price_Thursday, Price_Friday FROM Price"
            'Extract data
            SQLreader = SQLcommand.ExecuteReader()

            Cost_Monday = SQLreader("Price_Monday")
            Cost_Tuesday = SQLreader("Price_Tuesday")
            Cost_Wednesday = SQLreader("Price_Wednesday")
            Cost_Thursday = SQLreader("Price_Thursday")
            Cost_Friday = SQLreader("Price_Friday")

            'Clear SQL command buffer
            SQLcommand.Dispose()

            'Calculate Cost per day
            If Monday = True Then
                Total_Monday = sesmon * Cost_Monday
            Else
                Total_Monday = 0
            End If

            If Tuesday = True Then
                Total_Tuesday = sestue * Cost_Tuesday
            Else
                Total_Tuesday = 0
            End If

            If Wednesday = True Then
                Total_Wednesday = seswed * Cost_Wednesday
            Else
                Total_Wednesday = 0
            End If

            If Thursday = True Then
                Total_Thursday = sesthur * Cost_Thursday
            Else
                Total_Thursday = 0
            End If

            If Friday = True Then
                Total_Friday = sesfri * Cost_Friday
            Else
                Total_Friday = 0
            End If

            'Calculate week cost

            weekcost = weekcount * Cost_Monday

            'calculate term cost

            termtotal = Total_Monday + Total_Tuesday + Total_Wednesday + Total_Thursday + Total_Friday

            counter = counter + 1



        End If





    Loop






End Sub

由于

3 个答案:

答案 0 :(得分:1)

您可以将所有这些内容压缩为单个sql语句,并极大地减少您的代码:

Sub Cmd_CalculateClick(sender As Object, e As EventArgs)
   Dim sql As String = _
   "SELECT Pupil_ID, " & _
              "CASE WHEN Attendance_Monday    = 'T' THEN p.Price_Monday    ELSE 0 END " & _
            "+ CASE WHEN Attendance_Tuesday   = 'T' THEN p.Price_Tuesday   ELSE 0 END " & _
            "+ CASE WHEN Attendance_Wednesday = 'T' THEN p.Price_Wednesday ELSE 0 END " & _ 
            "+ CASE WHEN Attendance_Thursday  = 'T' THEN p.Price_Thursday  ELSE 0 END " & _
            "+ CASE WHEN Attendance_Friday    = 'T' THEN p.Price_Friday    ELSE 0 END " & _
        "As weekTotal, " & _
              "CASE WHEN Attendance_Monday    = 'T' THEN p.Price_Monday    * Session_Monday    ELSE 0 END " & _
            "+ CASE WHEN Attendance_Tuesday   = 'T' THEN p.Price_Tuesday   * Session_Tuesday   ELSE 0 END " & _
            "+ CASE WHEN Attendance_Wednesday = 'T' THEN p.Price_Wednesday * Session_Wednesday ELSE 0 END " & _
            "+ CASE WHEN Attendance_Thursday  = 'T' THEN p.Price_Thursday  * Session_Thursday  ELSE 0 END " & _
            "+ CASE WHEN Attendance_Friday    = 'T' THEN p.Price_Friday    * Session_Friday    ELSE 0 END " & _
        "As termTotal " & _ 
    "FROM Pupil p " & _
    "INNER JOIN Session s ON 1=1 " & _
    "INNER JOIN Price p ON 1=1 " & _
    "WHERE p.Waiting_List = 'F'"

    Using cn As New SqlConnection("connection string here"), _
          cmd As New SqlCommand(sql, cn)
        cn.Open()
        Using rdr As SqlDataReader = cmd.ExecuteReader()
           While rdr.Read() 
               Dim pupilID   As Integer = Convert.ToInt32(rdr("Pupil_ID"))
               Dim weekTotal As Decimal = Convert.ToDecimal(rdr("weekTotal"))
               Dim termTotal As Decimal = Convert.ToDecimal(rdr("termTotal"))
           End While
        End Using
    End Using
End Sub

当然我不知道你想用这些数字做什么,但是如果你只是想把它写回某个地方的数据库,你甚至可以在查询中包含它,而且永远不需要将结果全部读入VB端。这将极大地提高您的表现。

答案 1 :(得分:0)

if(SQLreader.HasRows)
{
   //....
}

在尝试从中获取Pupil_ID之前尝试此操作。

答案 2 :(得分:0)

您可以更改代码以使用ExecuteScalar并使用参数化查询

SQLcommand.CommandText = "SELECT Pupil_ID FROM Pupil " & _
                         "WHERE Pupil_ID = @cnt AND Waiting_List = 'F' "
SQLcommand.Parameters.AddWithValue("@cnt", counter.ToString)
Dim result = SQLcommand.ExecuteScalar()
if result Is Nothing then 
    Continue Do
else
    valid_user = Convert.ToInt32(result)
    .... continue with the rest of your code

这将有助于提高性能,因为ExecuteScalar可能比创建SqlDataReader的实例更快。在Do ...循环外创建命令并更新循环内的参数值

,可以实现另一点性能提升
Sub Cmd_CalculateClick(sender As Object, e As EventArgs)
    weekcount = 0

    SQLcommand = SQLconnect.CreateCommand
    SQLcommand.CommandText = "SELECT Pupil_ID FROM Pupil " & _
                             "WHERE Pupil_ID = @cnt AND Waiting_List = 'F' "
    SQLcommand.Parameters.AddWithValue("@cnt", "") 'dummy value here'

    Do Until counter = 9999
        valid_user = 0
        SQLcommand.Parameters("@cnt").Value = counter.ToString
        Dim result = SQLcommand.ExecuteScalar()
        if result Is Nothing then 
           Continue Do
        else
           valid_user = Convert.ToInt32(result)
           .... continue with the rest of your code
           .... but not destroy the command until the loop exit