Whats the best way to update a single record via SQL and obtain the id of the record that was updated? (Java/MSSQL)

前端 未结 4 544
刺人心
刺人心 2021-01-16 19:06

I know I can update a single record like this - but then how to I get access to the id of the record that was updated? (I\'m using MSSQL so I can\'t use Oracles RowId)

相关标签:
4条回答
  • 2021-01-16 19:43

    For insert MSQSQL server has the @@Identity parameter which has the ID of the last inserted record.

    0 讨论(0)
  • 2021-01-16 19:45

    Does this have to be in a single statement? Ultimately this would be best as a stored procedure

    Create Procedure doMyUpdate
    
     @Id int output
    
    as
    
    Set @Id = (select top 1 itemId from myTable)
    update myTable
    set myCol = 'foo'
    where itemId = @Id
    

    another way would be to use th RETURN keyword and the built in RETURN_VALUE parameter...

    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 讨论(0)
  • 2021-01-16 19:50

    This example works really well in 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]
    

    And more specifically to your query...

    update myTable
    set myCol = 'foo'
    output inserted.itemid
    where itemId in (select top 1 itemId from myTable )
    
    0 讨论(0)
  • 2021-01-16 19:58

    I would do the following:

    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 讨论(0)
提交回复
热议问题