我需要从表中获取最后一个ID并显示它。我已经尝试过Scope_Identity(),但不知怎的,我无法得到它。消息框没有显示任何内容..它是空的。这是我目前的代码:
Try
myConn.ConnectionString = "Data Source=192.168.2.222;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=sa;"
myConn.Open()
myCmd = New System.Data.SqlClient.SqlCommand("SELECT SCOPE_IDENTITY AS LastId FROM customers", myConn)
oResult = myCmd.ExecuteScalar()
If oResult IsNot Nothing Then
MsgBox(oResult.ToString)
Else
MsgBox("No Record Found")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
myConn.Close()
End Try
答案 0 :(得分:2)
如果您的I列是数字,则可以使用max:
SELECT MAX(ID) AS LastId FROM customers
答案 1 :(得分:0)
尝试==>
SELECT TOP 1 ID AS LastId FROM customers ORDER BY ID DESC
这假设您的“客户”表中有一个ID列,即您的PK。