I have a data repository layer which accesses an SQL table on our database called Form
.
I am trying to write a Merge
statement which inserts a new Id which is a GUID and updates the record if there is already an Id. However, my issue is that I do not know the Id if one isn't created.
I cannot get my head around it. This has made me thinking whether my statement would actually work at all.
This is my code:
conn.ExecuteScalar<Guid>(
"MERGE INTO [dbo].[Form] AS TARGET USING(VALUES(@Id,@CreatedAt,@IsComplete,@Data)) AS SOURCE(Id,CreatedAt,IsComplete,[Data]) " +
"ON TARGET.Id = SOURCE.Id WHEN MATCHED THEN " +
"UPDATE SET CreatedAt = SOURCE.CreatedAt,IsComplete = SOURCE.IsComplete, [Data] = SOURCE.[Data] " +
"WHEN NOT MATCHED BY TARGET THEN " +
"INSERT(Id,CreatedAt,IsComplete,[Data]) " +
"VALUES(newId(),CreatedAt,IsComplete,[Data]) OUTPUT INSERTED.Id " +
"new{Id = ??????, CreatedAt = enquiry.EnquiryDate, IsComplete = 1, Data = doc});
I am not sure what to put in the New for Id (I left it with ???). The enquiry is an object which contains some data from another table and the doc is an XML document.
Any suggestions on this would be a great help.