如果存在于SQL Server表中则更新

时间:2013-12-27 12:28:45

标签: c# asp.net sql sql-server

如果BatchNumber(在我的情况下)存在,如何更新整行?

在我的表中,批号是唯一的,如果Batchnumber存在,我需要更新整行或数量列

请帮助我以正确的方式做到这一点

{
    var conn = new SqlConnection(GetConnectionString());
    var StrBuilder = new StringBuilder(string.Empty);
    var splitItems = (string[])null;

    foreach (string item in SC_PurLinr)
    {
        const string sqlStatement = "INSERT INTO DEL_Stores (DealerCode, Code, Qty, ExpireDate, BatchNumber) VALUES";

        if (item.Contains(","))
        {
            splitItems = item.Split(",".ToCharArray());
            StrBuilder.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3], splitItems[4]);
        }
    }

    try
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(StrBuilder.ToString(), conn) { CommandType = CommandType.Text };
        cmd.ExecuteNonQuery();
        wucMessagePopup1.showPopup(1, string.Empty, "Record Saved Successfully.");
    }
    catch (SqlException ex)
    {
    }
    finally
    {
        conn.Close();
    }
}

3 个答案:

答案 0 :(得分:4)

使用SQL Server 2008中的MERGE:

WITH new_rows (
    SELECT @value value 
        ,@BatchNumber BatchNumber)
MERGE DEL_Stores target
USING new_rows source ON source.BatchNumber = target.BatchNumber
WHEN MATCHED THEN
    UPDATE SET value = @value
WHEN NOT MATCHED THEN
    INSERT (    
        BatchNumber
        ,value)
    VALUES(
        source.BatchNumber
        source.value);

答案 1 :(得分:1)

您可以通过存储过程以更好的方式实现此目的。

你的程序应该是这样的。

create PROCEDURE usp_Namae
         @parmeter INT
    ,@parmeter INT
    ,@BatchNumber INT
AS
BEGIN
    IF NOT EXISTS (
            SELECT *
            FROM tblname
            WHERE BatchNumber = @BatchNumber
            )
    BEGIN
        --INSERT query
    END
    ELSE
    BEGIN
        --Update query
    END
END

答案 2 :(得分:1)

只需在插入数据之前添加IF语句,如下所示:

IF  EXISTS (select * from sys.columns where object_id = OBJECT_ID(N'DEL_Stores') and name='BatchNumber')
BEGIN
// Do insert here
END