简体   繁体   English

从合并语句生成ID(GUID)

[英]Generate an Id (GUID) from a Merge Statement

I have a data repository layer which accesses an SQL table on our database called Form . 我有一个数据存储库层,可访问我们数据库中名为Form的SQL表。

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. 我正在尝试编写一个Merge语句,该语句插入一个新的ID(即GUID)并更新记录(如果已经有一个ID)。 However, my issue is that I do not know the Id if one isn't created. 但是,我的问题是,如果未创建ID,我将不知道该ID。

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 ???). 我不确定要在Id的新代码中添加什么(我将其保留为???)。 The enquiry is an object which contains some data from another table and the doc is an XML document. 查询是一个对象,其中包含来自另一个表的一些数据,而doc是XML文档。

Any suggestions on this would be a great help. 关于此的任何建议将是很大的帮助。

Consider moving the responsibility of creating a new GUID to your repository instead of having SQL Server create it for you. 考虑将创建新GUID的责任移到存储库中,而不是让SQL Server为您创建它。

Hopefully in your repository you know whether you have a ID for the record you are working with or whether it is a new document that does not yet have an ID assigned. 希望在您的存储库中,您知道您是否拥有正在使用的记录的ID,或者它是否是尚未分配ID的新文档。

In the event that you do not have an ID for the current document, use C# to create a new GUID for you. 如果您没有当前文档的ID,请使用C#为您创建一个新的GUID。 From here on out the code would be the same regardless of whether you are editing an existing record or creating a new record: You simply pass the ID variable to the SqlCommand (ideally as a Parameter). 从现在开始,无论您是编辑现有记录还是创建新记录,代码都是相同的:您只需将ID变量传递给SqlCommand(理想情况下作为参数)。

In your WHEN NOT MATCHED statement you can simply refer to SOURCE.Id instead of using newId(). WHEN NOT MATCHED语句中,您可以简单地引用SOURCE.Id而不是使用newId()。

Since you created the GUID in the repository, you already know what the value is should you need to use it as part of another operation (no need to return it from SQL Server). 由于您在存储库中创建了GUID,因此您已经知道该值是什么,您需要将该值用作其他操作的一部分(无需从SQL Server返回它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM