1

我需要从表中获取最后一个 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
4

2 回答 2

2

如果您的 Id 列是数字,您可以使用 max :

 SELECT MAX(ID) AS LastId FROM customers
于 2014-01-10T00:37:58.960 回答
0

试试==>

SELECT TOP 1 ID AS LastId FROM customers ORDER BY ID DESC

这假设您的“客户”表有一个 ID 列,即您的 PK。

于 2014-01-10T00:26:14.820 回答