我需要从SQL查询中获取最大值并将其保存到变量中

时间:2014-06-19 23:19:31

标签: list sql-server-ce vb.net-2010

这就是我所拥有的。

cmd = New SqlCeCommand("SELECT SUBSTRING(column, 10, 4) AS serial FROM main1 WHERE (SUBSTRING(column, 1, 3) = 'CAR')", cnx)
If cnx.State = ConnectionState.Closed Then cnx.Open()
Dim SerialStr As String
Dim SerialList As New List(Of Integer)
Using sdr As SqlCeDataReader = cmd.ExecuteReader()
    While sdr.Read()
        SerialList.Add(sdr.GetInt32(sdr.GetOrdinal("serial"))) 'I got this from a forum, not sure if it is what I need
    End While
    SerialStr = SerialList.Item(SerialList.Count).ToString
End Using

我尝试从中获取数据的列是主键,这是格式:

  

CAR2014-S0001

     

CAR2014-S0007

     

PAR2014-S0001

     

CAR2014-S0004

     

PAR2014-S0002

正如您所看到的,他们并没有按顺序排列。我需要从查询中获取每个数字的最后四位数,对它们进行排序,得到最后一个并将其分配给变量。

1 个答案:

答案 0 :(得分:0)

这样做:

cmd = New SqlCeCommand("SELECT max(right(column, 4)) AS serial FROM main1 WHERE (SUBSTRING(column, 1, 3) = 'CAR')", cnx)
If cnx.State = ConnectionState.Closed Then cnx.Open()
Dim SerialStr As String = cmd.ExecuteScalar()