SQL语句转到下一个可用号码

时间:2012-09-15 17:28:42

标签: vb.net-2010

我有一个名为DUI_Database的数据库。里面是一个名为DUI_Cite_Numbers的表。有两列-dui_cite_no和status。我有一些代码从两个文本框中获取一系列数字并将它们放在表中。此外,状态列是FREE或ALLOCATED。使用了分配的号码,不能重复使用。免费只是可用的数字。

如果你查看表格,它会是这样的,假设我输入了从D100100到D100105的范围

    DB Name: DUI_Database
    Table Name: DUI_Cite_Numbers

    dui_cite_no   status
    D100100       FREE
    D100101       FREE
    D100102       FREE
    D100103       FREE
    D100104       FREE
    D100105       FREE

然后,一旦使用这些数字,它就会像这样 -

    dui_cite_no   status
    D100100       ALLOCATED
    D100101       ALLOCATED
    D100102       ALLOCATED
    D100103       FREE
    D100104       FREE
    D100105       FREE

我需要SELECT语句的帮助。当表单打开时,我需要在该表单的文本框中使用下一个免费的dui_cite_no。我不知道如何做到这一点。

我认为这会奏效 -

    "SELECT TOP(1) dui_cite_no FROM DUI_Cite_Numbers WHERE status = 'FREE'"

它不起作用 - 看起来不对吗?

因为一旦使用它,它会在列中将其标记为ALLOCATED -

    "UPDATE DUI_Cite_Numbers SET status = 'ALLOCATED' WHERE dui_cite_no = @nextcit"

我很困惑,可能是因为我已经开始这么久了。

这是整个代码块:

Public Function Get_Next_DUI_Cit_Number() As String
    ''Get the next available citation number from the database. If there is no free
    ''citation number then return a null string
    Dim nextcit As String = String.Empty
    Using DataConnection As New System.Data.SqlServerCe.SqlCeConnection("Data Source=C:\Program Files\DailyLog DUI\DUI_Database.sdf")
        DataConnection.Open()
        Dim SelectCommand As New System.Data.SqlServerCe.SqlCeCommand("SELECT TOP(1) dui_cite_no FROM DUI_Cite_Numbers WHERE status = 'FREE'", DataConnection)
        Dim DataReader As System.Data.SqlServerCe.SqlCeDataReader = SelectCommand.ExecuteReader()
        If DataReader.Read() Then
            nextcit = DataReader("dui_cite_no").ToString
            Using DataConnection2 As New System.Data.SqlServerCe.SqlCeConnection("Data Source=C:\Program Files\DailyLog DUI\DUI_Database.sdf")
                DataConnection2.Open()
                Dim UpdateCommand As New System.Data.SqlServerCe.SqlCeCommand("UPDATE DUI_Cite_Numbers SET status = 'ALLOCATED' WHERE dui_cite_no = @nextcit", DataConnection2)
                UpdateCommand.Parameters.AddWithValue("@nextcit", nextcit)
                UpdateCommand.ExecuteNonQuery()
                UpdateCommand.Dispose()
                DataConnection2.Close()
            End Using
        End If
        SelectCommand.Dispose()
        DataConnection.Close()
    End Using
End Function

然后,当相应的表单打开时,这就是代码:

Public Sub frmDUI_Citation_Load(ByVal sender As System.Object,ByVal e As System.EventArgs)处理MyBase.Load

    Me.txt_dui_cite_no.Text = module1.Get_Next_DUI_Cit_Number() 'get the next available citation number and put it in the textbox

End Sub

1 个答案:

答案 0 :(得分:0)

如果您想确保按顺序发布,则需要添加ORDER BY

SELECT TOP(1) 
  dui_cite_no 
FROM 
  DUI_Cite_Numbers 
WHERE 
  status = 'FREE'
ORDER BY 
  dui_cite_Number