通过DataAdapter InsertCommand

时间:2017-05-14 23:39:11

标签: c# sql-server

存储过程代码:

ALTER PROCEDURE [dbo].[procInsertComputer]
    @pName NVARCHAR(128),
    @pDomain NVARCHAR(25) = NULL,
    @pStatus NCHAR(2) = NULL,
    @pNotes NVarChar(2000) = NULL
AS
    SET NOCOUNT ON
    DECLARE @NewID [int]

    IF NOT EXISTS (SELECT 1 FROM tbComputers WHERE Name=@pName)
    BEGIN
        INSERT INTO tbComputers (Name, Domain, Status, Notes)
        VALUES (@pName, @pDomain, @pStatus, @pNotes)

        SET @NewID = SCOPE_IDENTITY()
    END
    ELSE
    BEGIN
        SET @NewID = -1
    END

RETURN @NewID

Insert触发代码:

ALTER TRIGGER [dbo].[tr_tbComputer_Insert] 
ON [dbo].[tbComputers] 
FOR INSERT 
AS
    INSERT INTO tbComputers_Audit(id, Name, Domain, Status, Notes, AuditAction)
        SELECT 
            id, Name, Domain, Status, Notes, 'I' 
        FROM 
            Inserted

CreateAdapter代码:

public static SqlDataAdapter CreateAdapter(SqlConnection connection)
{
    if (connection == null)
    {
        throw new ArgumentNullException("connection");
    }

    var command = new SqlCommand("SELECT Name, Domain, Status, Notes FROM tbComputers", connection);

    var adapter = new SqlDataAdapter(command);

    adapter.RowUpdated += (sender, update) =>
    {
        if (update.Status != UpdateStatus.Continue ||
            update.StatementType != StatementType.Insert)
        {
            return;
        }

        var idCommand = new SqlCommand("SELECT SCOPE_IDENTITY()", connection);

        update.Row["Id"] = idCommand.ExecuteScalar();
    };

    var insertCommand = new SqlCommand("procInsertComputer", connection)
    {
        CommandType = CommandType.StoredProcedure
    };

    insertCommand.Parameters.Add("@pName", SqlDbType.VarChar, 128, "Name");
    insertCommand.Parameters.Add("@pDomain", SqlDbType.VarChar, 25, "Domain");
    insertCommand.Parameters.Add("@pStatus", SqlDbType.Char, 2, "Status");
    insertCommand.Parameters.Add("@pNotes", SqlDbType.VarChar, 2000, "Notes");

    adapter.InsertCommand = insertCommand;

    return adapter;
}

测试代码:

// Create objects
var databaseConnection = "my connection string"
var adapter = CreateAdapter(databaseConnection)
var dataSet = new Dataset();

// Fill data
adapter.Fill(dataSet, "Table");

// Create new row
var newRow = dataSet.Tables[0].NewRow();
dataSet.Tables[0].Rows.Add(newRow);

// Populate columns
newRow.Name = "TestServer01"
newRow.Status = "BU"
newRow.Domain = "TestLab01.test.au"
newRow.Notes = "test creation via C#"

// Accept changes
adapter.Update(dataSet.Tables[0]);

问题:插件工作正常,并将新行添加到表中,并且它拥有唯一生成的ID,但我在C#中拥有的DataRow对象获取的ID触发器插入。

问题:更新新的RETURN时,是否可以通过InsertCommand DataRow轻松更新ID?

研究:很多人根据我发现的答案建议SELECT SCOPE_IDENTITY()让我更接近,因为它现在正在更新ID,它只是没有更新到正确的ID。

0 个答案:

没有答案