What is the best way to update a single record through SQL and get the ID of the updated record? (Java / MSSQL)

I know that I can update one record like this, but how do I access the ID of the updated record? (I use MSSQL, so I can not use Orales RowId)

update myTable
set myCol = 'foo'
where itemId in (select top 1 itemId from myTable )

If I formatted Insert, I could use getGeneratedKeys to get the id field value, but I don’t think there is an equivalent for updating?

I know that I can use a scrollable result set to do what I want

i.e.

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();

but performance bothers me, as testing shows lockout timeouts under load, and I was wondering if there was a better / easier way?

- EDIT: ... MSSQL2005, , Rich-. : (UPDLOCK ROWLOCK READPAST), , .

0
4

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 )
+6

:

Begin Tran

update myTable
set myCol = 'foo'
where itemId in (select top 1 itemId from myTable )

select top 1 itemId from myTable

Commit Tran
0

?

Create Procedure doMyUpdate

 @Id int output

as

Set @Id = (select top 1 itemId from myTable)
update myTable
set myCol = 'foo'
where itemId = @Id

RETURN RETURN_VALUE...

Create Procedure doMyUpdate

as

Declare @Id int
Set @Id = (select top 1 itemId from myTable)

update myTable
set myCol = 'foo'
where itemId = @Id

RETURN @Id
0

Insert server MSQSQL has a parameter @@Identitythat has the identifier of the last inserted record.

-4
source

Source: https://habr.com/ru/post/1703361/


All Articles