vb.net 获取最后一个 ID 并显示它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21033899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:24:29  来源:igfitidea点击:

vb.net get the last ID and display it

sql-servervb.netscope-identity

提问by user3105451

i need to get the last ID from a table and display it. I've tried Scope_Identity() but somehow i could not manage to get it. the message box shows nothing.. it's empty. here is my current code:

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

回答by Al-3sli

If your I'd column is numeric you can use max :

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

 SELECT MAX(ID) AS LastId FROM customers

回答by robnick

Try ==>

试试==>

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

This assumes that your 'customers' table has an ID column which is your PK.

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