I am trying to bulk insert the records in sql server. I am using User Defined Table type to pass the collection of records from my .net application. Please take a look at the insert query below.
INSERT INTO MachineItems([Name],[Price],[Quantity],[ItemGroupID],[SubGroup] ,[IsDefault],
[IsRemovable],[MachineTypeID],[ItemType],[CreatedBy],[CreatedOn] )
SELECT mi.Name
,mi.Price
,mi.Quantity
,(SELECT ID from ItemGroups WHERE NAME=mi.ItemGroup) as ID
,mi.SubGroup,
CASE
WHEN mi.IsDefault ='Yes' THEN 1
WHEN mi.IsDefault ='No' THEN 0
WHEN mi.IsDefault IS NULL THEN 0
END ,
CASE
WHEN mi.IsRemovable ='Yes' THEN 1
WHEN mi.IsRemovable ='No' THEN 0
END ,
(SELECT ID from MachineTypes WHERE Name=mi.MachineType),
(SELECT ID from MachineItemTypes WHERE Name=mi.ItemType),
mi.CreatedBy
,mi.CreatedOn
FROM @MachineItems mi
What i want to do is put the check before inserting the records , Whether record with [MachineTypeID] and [Name] already exists in table or not. If it does not exists then insert Eles Update the record.
How can i do that with User Defined Table Type ?
You should use the MERGE command rather than a straight insert. What you are wanting to do is not really specific to User-Defined Table Types.
It would be better / more efficient if you joined the 3 subtables rather than having subqueries for columns which will execute per-row.
Example: