通过SQL更新单个记录并获取已更新记录的id的最佳方法是什么?(Java/MSSQL)[英] Whats the best way to update a single record via SQL and obtain the id of the record that was updated? (Java/MSSQL)

问题描述

我知道我可以像这样更新单个记录 - 但是如何访问已更新记录的 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 )

本文地址:https://www.itbaoku.cn/post/978524.html