I have a large amount of data that I would like to send from a C# web application to a SQL Server database. At present I iterate over the data in loops and call stored procedures to add the data. I return the PK of the inserted (or existing) Client record and add this to the foreign key of the associated activity records and then add them. I'm aware that this is not very efficient and have since been investigating the use of table-valued parameters.
My dataset is similar to the following:
Client (ID, FirstName, Surname, DOB ...)
Activity1 (ID, ClientID(FK), Date ...)
Activity2 (ID, ClientID(FK), Date ...)
I would like to add all clients as a bulk insert and return the ID's using the OUTPUT clause in SQL Server and then add their associated activity with these ID's as the PK-FK relationship. The only thing I cant figure out is how to check if a client already exists (based on FirstName, Surname and DOB being the same) in the database and if so return that ID instead of adding the client in as a new record.
As a test, I have created a stored procedure that accepts a TVP like so:
CREATE PROCEDURE [dbo].[TestBulkAdd]
@Data AS dbo.Data READONLY
AS
BEGIN
DECLARE @IDS TABLE (ID INT, FirstName NVARCHAR(50), Surname NVARCHAR(50), DOB DATETIME2)
INSERT INTO Clients (FirstName, Surname, DOB)
OUTPUT inserted.* INTO @IDS
SELECT * FROM @Data
SELECT * FROM @IDS --Fills datatable in C# with returned data
END
GO
Any help would be greatly appreciated.