防止重复条目插入SQL Server db?

时间:2013-05-20 12:16:32

标签: sql if-statement xmlhttprequest duplicates

net,razor,webmatrix,使用.cshtml页面。

我使用jQuery打开模态表单并使用该表单将数据插入SQL数据库(SQLExpress 2012)。我试图通过使用以下代码来限制重复的输入,但是从网页[object XMLHttpReques]获取消息。

AddDiscount.cshtml代码是:

@{


   if(IsPost){

        var db = Database.Open("A-LensCatFE-01SQL") ; 

        var CCode=UrlData[0];

        var Q1 = "SELECT * FROM dbo.tblPromos WHERE CustomerCode =@0";
        var ds = db.ExecuteDataSet(Q1, CCode);

        if(ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
          {
                 MessageBox.Show("Duplicates");
          }
        else
        {
        var sql = "INSERT INTO dbo.tblPromos (CustomerID, CustomerCode,  Discount, VAT, VATRate, iScription, SRPBasedOn)" + 
            "VALUES (@0, @1, @2, @3, @4, @5, @6)";

        var customerid = Request["customerid"];
        var customercode = Request["customercode"];
        var discount = Request["discount"];
        var vat = Request["vat"] == "on" ? true : false;
        var vatrate = Request["vatrrate"];
        var iscription = Request["iscription"];
        var srpbasedon = Request["srpbasedon"];

        db.Execute(sql, customerid, customercode,  discount, vat, vatrate, iscription, srpbasedon);

        }
       }
 }

需要你的帮助,非常感谢。

存储过程代码是:

创建程序dbo.spDiscDup

@CustomerID int =NULL,
@CustomerCode nvarchar(max)=NULL,
@Discount decimal(5,2)=NULL,
@VAT bit =NULL,
@VATRate decimal (5,2)=NULL,
@iScription money=NULL,

    AS
    BEGIN
IF EXISTS(SELECT * FROM tblPromos WHERE CustomerCode=@CustomerCode)
 ("Duplicates")
  ELSE
 INSERT INTO dbo.tblPromos (CustomerID, CustomerCode,  Discount, VAT, VATRate,            iScription, SRPBasedOn)" + 
          "VALUES (@0, @1, @2, @3, @4, @5, @6)

END GO

1 个答案:

答案 0 :(得分:0)

尝试使用存储过程并在插入之前检查记录是否存在。

If not exist 
 Then insert it
Else
 Return -1 -- means records exist/ Your prefer Msg/ any number