使用VB.net在SQL Server 2008中选择上次插入的记录 [英] Select Last Inserted Record in SQL Server 2008 using VB.net

查看:74
本文介绍了使用VB.net在SQL Server 2008中选择上次插入的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的表格架构

Here is my table schema

CustomersID         uniqueidentifier    (newid())
CompanyName         nvarchar(50)
RegistrantName  nvarchar(50)
AddressLine1    nvarchar(50)
AddressLine2    nvarchar(50)
City            nvarchar(50)
State           nvarchar(50)
Country         nvarchar(50)
Zip                 nvarchar(20)
PhoneNo         nvarchar(50)
MobileNo            nvarchar(20)
FaxNo           nvarchar(20)
Website         nvarchar(250)
Email           nvarchar(250)



由于我没有在表格中使用任何标识字段,因此我无法使用 SCOPE_IDENTITY()来获取最后插入的记录ID。插入记录后我需要获取 CustomersID 。这怎么可能?我正在使用 sqlcommand 类对象来插入记录。


As I''m not using any identity field in my table I cannot use the SCOPE_IDENTITY() to get the last inserted record id. I need to get the CustomersID after inserting the record. How is it possible? I''m using sqlcommand class object to insert the record.

推荐答案

在我看来,最好的方法是使用 OUTPUT [ ^ ]子句。因此,您可以修改insert语句并将其添加到SQL中。类似于:

In my opinion the best way would be to use the OUTPUT[^] clause. So you could modify your insert statement and add it to the SQL. Something like:
INSERT INTO MyTable (column1, column2) VALUES (...)
OUTPUT inserted.CustomersID INTO @customerid



只需记住为SqlParameter定义一个返回值。


Just remember to define a SqlParameter for the returning value.


SELECT TOP 1 * FROM table_Name ORDER BY unique_column DESC





试试这个。



Try this.


SELECT TOP 1 * FROM Customer ORDER BY CustomerID DESC





并将数据绑定到gridview或repeater。



and bind data to gridview or repeater.


这篇关于使用VB.net在SQL Server 2008中选择上次插入的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆