简体   繁体   中英

Updating data with same primary key

I am reading data from csv file and adding data in database. 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. So, when I insert data from csv file similar barcode quantity will get added.

Can anyone help me? I am using C#.NET and SQL.

Thanks, Rushabh Shah.

check out the merge keyword. 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:

  1. BULK INSERT the data from the CSV file to an empty temp table.
  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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