如果记录存在则删除,如果记录不存在则删除

时间:2016-07-25 16:29:34

标签: sql-server vb.net

在我的for循环中,我正在编写一个Insert和delete查询,它执行以下操作:

如果未选中复选框,则检查记录是否存在&如果存在则删除。如果它不存在则不要做任何事情。

如果选中复选框,则还要检查记录是否存在&如果它存在则不做任何事情,但如果它不存在则插入它。

我需要检查我的查询,特别是我的子查询是否会正确执行,或者是否会返回错误,因为我正在编写它而不想立即更改我的数据库。

For Each oDataGridItem In valgrid2.Items
        chk = oDataGridItem.FindControl("CheckBox1")
        rn = oDataGridItem.FindControl("lblrptName")
        rid = oDataGridItem.FindControl("lblReportID")
        If chk.Checked = True Then
            rpti = CType(oDataGridItem.FindControl("lblReportID"), Label).Text

            'valsql2 = "INSERT INTO CompanyReportListTable(CompanyID, ReportID) Values (valCompanyId, rpti) WHERE NOT EXISTS(SELECT * FROM CompanyReportListTable WHERE ReportID <> rpti and companyid <> valCompanyId and " & chk.Checked & "= 1)"
            'if it exists then don’t do anything
            'valsql2 = valsq2 & ";IF ReportID = rpti and companyid = valCompanyId BEGIN WHERE CompanyID = CompanyID AND ReportID = ReportID END" 
            'To do nothing, i'd equal the parameter's value to the column name

            count += 1
            rptn = CType(oDataGridItem.FindControl("lblrptName"), Label).Text
            oExArgs.Add(rptn)
            Response.Write(rpti + " - " + rptn + "<br/>")
        Else
            'valsql2 = valsq2 & ";DELETE FROM CompanyReportListTable WHERE EXISTS(Select * FROM CompanyReportListTable WHERE ReportID = rpti and companyid = valCompanyId and" & chk.Checked & " = 0)"
            'if it doesn't exist then don’t do anything
            'valsql2 = valsq2 & ";IF ReportID <> rpti and companyid <> valCompanyId BEGIN WHERE CompanyID = CompanyID AND ReportID = ReportID END" 

        End If

2 个答案:

答案 0 :(得分:1)

valsql2 = "INSERT INTO CompanyReportListTable(CompanyID, ReportID) Values (valCompanyId, rpti) WHERE NOT EXISTS(SELECT * FROM CompanyReportListTable WHERE ReportID <> rpti and companyid <> valCompanyId and " & chk.Checked & "= 1)"

在此代码" & chk.Checked & "= 1)"中会出错。 True = 1 ,这在sql中不受支持。

答案 1 :(得分:0)

如果您不希望代码执行任何操作,则不需要CASE语句,因为CASE可以使用SELECT语句。由于查询在If-Else语句下,因此valsql2 = whatever,而不是valsql2 = valsql2&amp; “;”因为这是条件语句,无论条件如何,查询都是如此。查询相当正常,只需摆脱chk.Checked = 0和chk.Checked = 1