简体   繁体   English

使用相同的主键更新数据

[英]Updating data with same primary key

I am reading data from csv file and adding data in database. 我正在从csv文件读取数据并在数据库中添加数据。 At time of inserting data into database I want to update data with same primary key. 在将数据插入数据库时​​,我想使用相同的主键更新数据。

eg) I am using two Columns Bar-codes (PK) and Quantity. 例如)我正在使用两个列条形码(PK)和数量。 So, when I insert data from csv file similar barcode quantity will get added. 因此,当我从csv文件插入数据时,将添加类似的条形码数量。

Can anyone help me? 谁能帮我? I am using C#.NET and SQL. 我正在使用C#.NET和SQL。

Thanks, Rushabh Shah. 谢谢,鲁沙巴·莎阿

check out the merge keyword. 查看merge关键字。 it should do pretty much waht you're asking for. 它几乎可以满足您的要求。

here's a stored proc that should do it for you. 这是应该为您完成的存储过程。

CREATE PROCEDURE dbo.InsertBarcodeData
    @Barcode varchar(255),
    @Quantity int
AS 
BEGIN
    SET NOCOUNT ON;

    MERGE myTableName AS target
    USING (SELECT @Barcode, @Quantity) AS source (BarCode, Quantity)
    ON (target.Barcode= source.Barcode)
    WHEN MATCHED THEN 
        UPDATE SET Quantity = source.Quantity + target.Quantity
    WHEN NOT MATCHED THEN   
        INSERT (BarCode, Quantity)
        VALUES (source.BarCode, source.Quantity)
END;
GO
create procedure InsertOrUpdateSales
(
    @bar_code nvarchar(100),
    @quantity int
)
as
if exists (select * from sales where bar_code = @bar_code)
  update sales set quantity = quantity + @quantity where bar_code = @bar_code
else
  insert into sales ( bar_code, quantity) values ( @bar_code, @quantity )
go

And

public static void InsertOrUpdateSales(string connection, string barCode, int quantity)
{
    using(SqlConnection conn = new SqlConnection(connection))
    {
        using(SqlCommand comm = new SqlCommand("InsertOrUpdateSales", conn))
        {
             comm.CommandType = CommandType.StoredProcedure;
             comm.Paramters.AddWithValue("@bar_code", barCode);
             comm.Paramters.AddWithValue("@quantity", quantity);
             comm.ExecuteNonQuery();
         }
     }
}

Alternatively, if you want to use the merge statement (as @Chris Lively and @nathan gonzalez mentioned) you could get really fancy and do it like this: 另外,如果您想使用merge语句(如@Chris Lively和@nathan gonzalez提到的),则可能会非常喜欢并做到这一点:

  1. BULK INSERT the data from the CSV file to an empty temp table. 将CSV文件中的数据批量插入到空的临时表中。
  2. MERGE the temp table with the existing table. 将临时表与现有表合并。
  3. TRUNCATE the temp table. 截断临时表。

This might give you the best results. 这可能会给您最好的结果。 (For certain values of "best".) (对于“最佳”的某些值。)

如果可以假定表中所有条形码已经存在条目,则可以使用带有两个incominig参数(@BarCodeID和@AdditionalQuantity)的存储过程来完成此操作。

UPDATE yourTable SET Quantity = Quantity + @AdditionalQuantity WHERE BarCode = @BarCodeID

You can add a Trigger to the table. 您可以将触发器添加到表中。 When ever something is inserted in the table, you can have it run a stored procedure. 在表中插入任何内容时,都可以运行存储过程。

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

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