I need to update several rows from a table in a single operation.
What I'd normally do, is to delete (soft delete) all previous records with the same foreign key and insert everything again. But this is not optimal at all and now that my job actually involves having to create stored procedures I wanted to know it there was a 'standard' way to perform this kind of operations.
Take these images as an example:
This is the original data associated with the foreign key (
ParentId
) 1:Then using the corresponding interface I make the following changes:
a) In the second row, the column
Name
(in yellow) was changed
b) The third row (in red) was removed
c) The fourth and fifth rows (in green) are new. Because these rows reside only on the client side I don't have a primary key (Id) for themThis is what I would like to end up with:
So far I've created a new type :
IF EXISTS(SELECT * FROM sys.types WHERE name='T_DetailDomain') BEGIN
DROP TYPE dbo.T_DetailDomain;
END;
GO
CREATE TYPE dbo.T_DetailDomain AS TABLE
(
Id INT NOT NULL,
Name VARCHAR (50) NOT NULL,
Abbrev VARCHAR (300) NOT NULL,
ParentId INT NOT NULL
);
GO
And this is the signature of the procedure:
CREATE PROC dbo.up_DetailDomain_Update
@pParentId INT,
@pTableDetail dbo.T_DetailDomain READONLY
AS
As you can see I pass all the rows as a table-valued parameter (@pTableDetail
).
Is there any 'standard' way I can achieve what I described above?
Or do I have to perform three operations:
- Insert all the rows without an Id
- update all the rows with an existing Id
- remove all the rows with an Id not present in the table-valued parameter?
Thanks.