当多个单元格具有相同的ID时,如何仅删除所选行?

时间:2019-04-04 10:42:05

标签: c# sql-server asp.net-mvc tsql stored-procedures

我正在设置一个存储过程,以根据用户选择的选项删除特定的行。该存储过程获取了2个id,并检查它们是否在表中。但是我无法弄清楚。你能帮忙吗?

我的存储过程如下

@idcliente numeric,
@codmedia numeric
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON; 
    IF (EXISTS(SELECT COD_MEDIA FROM MEIOS_CLIENTES WHERE ID_CLIENTE = @idcliente AND COD_MEDIA = @codmedia))
    BEGIN
        DELETE FROM MEIOS_CLIENTES WHERE ID_CLIENTE = @idcliente AND COD_MEDIA = @codmedia
    END     
END

数据库中的表如下

COD_SERVICO | ID_CLIENTE
     1            2
     26           2
     1            1
     32           1

表中有很多记录。

想象一下,如果用户选择从ID_CLIENTE 2中删除COD_SERVICO 1。

编辑:

我正在通过jquery进行操作请求,代码如下:

function removeMeioCliente(idcliente ,idservico) {


    bootbox.dialog({
        message: "Irá eliminar o serviço selecionado. Deseja continuar?",
        title: "Alerta - Eliminação do Serviço",
        buttons: {

            danger: {
                label: "Cancelar",
                className: "btn-danger",
                callback: function () {
                }
            }, success: {
                label: "Continuar",
                className: "btn-success",
                callback: function () {

                    var options = {
                        url: baseurlrequest + 'cliente/deleteservico',
                        params: {
                            id2: idcliente,
                            id: idservico,
                        },
                        onsuccess: displaydeleteservico
                    }

                    $.fn.ajaxpostjson(options);

                }
            }
        }
    });
}


function displaydeleteservico(data) {
    if (data.status == 200) {
        toastr.info("Serviço eliminado com sucesso!", 'Cision Corpora');
    }

    if (data.status == 500) {
        toastr.error(data.html, 'Cision Corpora');
    }
}

在我看来,我的桌子是这样的。该项目是字符串,因为我正在测试是否传递了某些ID,两者均为空。

       <table class="table table-striped" cellspacing="0">
                            <thead>
                                <tr>
                                    <th class="th-sm">Meios do Cliente</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                            <tbody>

                                @foreach (var item in Model.Meios)
                                {
                                    <tr>
                                        <td>
                                            @Html.Raw(item.Item3)
                                        </td>
                                        <td onclick="removeMeioCliente(@item.Item1.ToString(),@item.Item2.ToString());"><i class="fa fa-times"></i></td>
                                    </tr>
                                }
                            </tbody>
                        </table>

为什么两个ID都为空?

编辑2:

我把它弄干净了!

如果有人想知道解决方案,我将发布代码。

在我看来,代码看起来像这样

 <td><a id="servicoidcliente" data-id="@item.Item1" onclick="removeMeioCliente(@item.Item2);"><i class="fa fa-times"></i></a></td>

然后在Jquery中添加了一条简单的行:

var idcliente = $('#servicoidcliente').data("id");

控制器:

public ActionResult DeleteServico(string id2,string id)
        {
            var statusreq = this.StatusOk;
            var html = "";    
            try
            {
               BusinessService.Cliente.RemoverServicoCliente(id2,id);
            }
            catch (Exception ex)
            {
                statusreq = this.StatusError;
                html = ex.Message;
            }
            return Json(new
            {
                id = id,
                id2 = id2
            },
            JsonRequestBehavior.AllowGet);
        }

2 个答案:

答案 0 :(得分:0)

这应该可行,您的问题是什么?

但是,您可以省略“ if”部分,如果与您的WHERE条件不匹配,删除将不会执行任何操作,但不会失败。

答案 1 :(得分:0)

您可以创建一个变量来接受用户输入,并根据COD_SERVICO的值删除选定的列。

-- Create demonstration table
IF OBJECT_ID('tempdb.dbo.#_test') IS NOT NULL DROP TABLE #_test
CREATE TABLE #_test (
    [ID] INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    [COD_SERVICO] VARCHAR(25) NULL,
    [ID_CLIENTE] VARCHAR(25) NULL,
)
INSERT INTO #_test ([COD_SERVICO], [ID_CLIENTE])
VALUES ('1','2'),
        ('26','2'),
        ('45','1'),
        ('32','1')

表值(带有ID列):

ID  COD_SERVICO ID_CLIENTE
1     1           2
2     26          2
3     45          1
4     32          1


-- Declare variable for input
DECLARE @_cod_servico_to_remove VARCHAR(25)

-- Set variable to whatever the user wants to remove.  This will impact the COD_SERVICO column
SET @_cod_servico_to_remove = '1'

-- Run your delee query (Transact-SQL)
DELETE FROM #_test
WHERE [COD_SERVICO] = @_cod_servico_to_remove

结果:

ID  COD_SERVICO ID_CLIENTE
2     26             2
3     45             1
4     32             1

编辑:这是一个与OP基本上相同的过程,但是会考虑缺失值。

--Clear any prior procedures
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.RemoveRecords') AND OBJECTPROPERTY(id,  N'IsProcedure') = 1) DROP PROCEDURE dbo.RemoveRecords;
GO

--Set two variables to null; Evaluate passed arguments inside the procedure.
CREATE PROCEDURE dbo.RemoveRecords
    @idcliente FLOAT = NULL,
    @codmedia FLOAT = NULL
AS
BEGIN

    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    DECLARE @_sql NVARCHAR(MAX)

    IF @idcliente IS NOT NULL AND @codmedia IS NOT NULL
        BEGIN
            IF (SELECT COUNT(*) FROM MEIOS_CLIENTES WHERE CONVERT(FLOAT, ID_CLIENTE) = @idcliente AND CONVERT(FLOAT, COD_MEDIA) = @codmedia) > '0'
                BEGIN
                    DELETE FROM MEIOS_CLIENTES
                    WHERE CONVERT(FLOAT, [ID_CLIENTE]) = @idcliente
                    AND CONVERT(FLOAT, [COD_SERVICO]) = @codmedia
                END;
        END;

END;
GO