我知道我可以像这样更新一条记录 - 但是如何才能访问已更新的记录的id?(我正在使用MSSQL,所以我不能使用Oracles RowId)
update myTable set myCol = 'foo' where itemId in (select top 1 itemId from myTable )
如果我正在使用插入,我可以使用getGeneratedKeys来获取id字段值,但我认为没有相应的更新?
我知道我可以使用可滚动的结果集来做我想要的
即
stmt = conn.prepareStatement("select top 1 myCol, itemId from myTable", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet resultSet = stmt.executeQuery(); if(resultSet.first()){ resultSet.updateString(1, "foo"); resultSet.updateRow(); String theItemId = resultSet.getString(1) } resultSet.close();
但我担心性能,因为测试显示负载下的锁定超时,我想知道是否有更好/更简单的方法?
- 编辑:刚刚完成这个问题......当我们迁移到MSSQL2005时,我们将升级我们的代码以使用Rich的答案.在当前版本中,我们使用了锁提示:(UPDLOCK ROWLOCK READPAST)来缓解原始代码显示的性能问题.
这个例子在MSSQL 2005中运行得很好......
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO DROP TABLE [dbo].[TEST_TABLE] GO CREATE TABLE [dbo].[TEST_TABLE]( [id] [int] IDENTITY(1,1) NOT NULL, [name] [nvarchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, CONSTRAINT [PK_TEST_TABLE] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] -- An insert which will return the identity INSERT INTO [dbo].[TEST_TABLE] ([name]) OUTPUT inserted.id VALUES('Test 1') -- Another insert which will return the identity INSERT INTO [dbo].[TEST_TABLE] ([name]) OUTPUT inserted.id VALUES('Test 2') -- Now an update which will return the identity UPDATE [dbo].[TEST_TABLE] SET [name] = 'Updated Test 1' OUTPUT inserted.id WHERE [name] = 'Test 1' SELECT id, [name] FROM [dbo].[TEST_TABLE]
更具体地说,你的查询......
update myTable set myCol = 'foo' output inserted.itemid where itemId in (select top 1 itemId from myTable )