Following is new data type that I created.
CREATE TYPE [dbo].[UpdateHotelTableType] AS TABLE(
[ID] [int] NULL,
[HotelID] [int] NULL,
[FromDate] [datetime] NULL,
)
Following is my stored procedure that I used the above datatype.
ALTER PROCEDURE [dbo].[SP_Hotel_Info_Update]
-- Add the parameters for the stored procedure here
@XHotelInfoDetails UpdateHotelTableType READONLY,
AS
BEGIN
Update dbo.HotelInfo
SET
FromDate = r.FromDate,
from @XHotelInfoDetails r
Where HotelInfo.ID = r.ID
END
This is working fine for update results in database. But I want to check whether the id is exists and if the id is not exists insert the row in to the table. otherwise update current record. In here I am sending the list of data for update.
Can any one help me to recreate the stored procedure to insert the data too by checking the existence of ID.
User-defined table types are the predefined tables that the schema definition is created by the users and helps to store temporary data. User-defined table types support primary keys, unique constraints and default values, etc.
User-defined tables represent tabular information. They are used as parameters when you pass tabular data into stored procedures or user-defined functions. User-defined tables cannot be used to represent columns in a database table.
Use MERGE
:
Performs insert, update, or delete operations on a target table based on the results of a join with a source table. For example, you can synchronize two tables by inserting, updating, or deleting rows in one table based on differences found in the other table.
ALTER PROCEDURE [dbo].[SP_Hotel_Info_Update]
-- Add the parameters for the stored procedure here
@XHotelInfoDetails UpdateHotelTableType READONLY,
AS
BEGIN
MERGE dbo.HotelInfo AS trg
USING @XHotelInfoDetails AS src
ON src.ID = trg.ID
WHEN MATCHED THEN
UPDATE SET FromDate = src.FromDate
WHEN NOT MATCHED BY TARGET THEN
INSERT (col1, col2, ...)
VALUES (src.col1, src.col2, ...);
END
EDIT:
In my datatable, there can be newly added rows as well as deleted rows. So how can I compare the id and delete rows from hotelinfo table?
You could add new clause:
WHEN NOT MATCHED BY SOURCE [ AND <clause_search_condition> ]
THEN DELETE;
with specific condition to delete data from target.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With