简体   繁体   English

保留记录的非插入数据

[英]Preserving non-inserted data for a record

I am experimenting with table valued parameters (TVP) and how to use them from C# code. 我正在尝试使用表值参数(TVP),以及如何从C#代码中使用它们。 One specific aspect of TVP is giving me trouble: When passing a list of data to the Stored Procedure and wanting to update that list after the data has come back from the database. TVP的一个特定方面给我带来麻烦:将数据列表传递给存储过程时,并希望在数据从数据库返回后更新该列表。

Here is a sample class that would be contained within a list: 这是一个将包含在列表中的示例类:

public class Phone
{
    int _phoneID;
    string _phoneNumber;
    Guid _correlationID;
}

When passing this list to a stored procedure that uses TVP, how would I be able to insert the _phoneID and the _phoneNumber into the database and, after the insert, update the list of Phones with the _phoneID based on the _correlationID? 当将此列表传递给使用TVP的存储过程时,如何将_phoneID和_phoneNumber插入数据库中,并在插入后根据_correlationID使用_phoneID更新电话列表?

Here is a sample table, type, and stored procedure: 这是一个示例表,类型和存储过程:

Create Table PhoneTable
(
    PhoneID int identity(1,1),
    PhoneNumber varchar(20)
)
GO

Create Type PhoneType As Table
(
    PhoneNumber varchar(20),
    CorrelationID uniqueidentifier
)
GO

Create Procedure usp_Phone_Insert
    @Input PhoneType ReadOnly
AS
    Declare @Output Table (PhoneID int, PhoneNumber varchar(20))

    Insert Phone (PhoneNumber)
    Output
        inserted.PhoneID,
        inserted.PhoneNumber
    Into @Output
    Select 
        PhoneNumber
    From
        @Input

    Select PhoneID, PhoneNumber From @Output
GO

The reason for a correlation id is for the ability to track the objects all the way from the application to the database and back. 相关ID的原因是能够跟踪从应用程序到数据库并一直追溯到对象的对象。

Based on the comment under my question about inner joins, I came to this solution and it looks to work very well. 基于我对内部联接的疑问,我得出了这个解决方案,它看起来工作得很好。 This approach will only work if the data that is being inserted is unique in the set. 仅当要插入的数据在集合中唯一时,此方法才有效。

Modified table, type and stored procedure to accomplish my needs for a correlation ID: 修改的表,类型和存储过程可以满足我对相关ID的需求:

Create Table PhoneTable
(
    PhoneID int identity(1,1),
    PhoneNumber varchar(20)
)
GO

Create Type PhoneType As Table
(
    PhoneNumber varchar(20),
    CorrelationID bigint
)
GO

Create Procedure usp_Phone_Insert
    @Input PhoneType ReadOnly
AS
    Declare @Output Table (
        PhoneID int, 
        PhoneNumber varchar(20),
        CorrelationID bigint)

    Insert Phone (PhoneNumber)
    Output
        inserted.PhoneID,
        inserted.PhoneNumber
    Into @Output
    Select 
        PhoneNumber
    From
        @Input

    Select
        O.PhoneID,
        O.PhoneNumber,
        I.CorrelationID
    From
        @Output O
        Inner Join @Input I on I.PhoneNumber = O.PhoneNumber
GO

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

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