jawed
jawed

Reputation: 51

How do I prevent update on wrong data?

I have a scenario, like I want insert a record into a table, then I update same record by getting the last inserted row Id, so now my issue is if a another user inserts a new record before the first record gets updated, so according to my scenario I get the last inserted row Id , in this case update applied on the last row instead of the first one, any solution please.

Upvotes: 0

Views: 189

Answers (1)

Jayasurya Satheesh
Jayasurya Satheesh

Reputation: 8043

This is for SQL Server if you have an Identity column in the Table, after inserting use the @@IDENTITY variable or SCOPE_IDENTITY() function to get the Identity value of the Row inserted and then while updating use the Identity Filed in the Where Clause.

Something like this

INSERT INTO MyTable(FullName)
VALUES('My Name')

SELECT @IdVal = SCOPE_IDENTITY()

UPDATE MyTable SET Phone='1234' WHERE IdCol = @IdVal

Upvotes: 2

Related Questions