SQL子查询从if else语句返回的值超过1

时间:2018-11-05 14:11:43

标签: sql tsql

这是我的存储过程之一的声明

String

问题是,我需要仅在IF @Action = 'UPDATE' BEGIN IF (Select Nome From hDados hd JOIN hRequisicao hr ON hr.IdReq = hd.IdReq WHERE hr.IdColaborador = 3 AND IdStatus != 4 AND IdStatus != 5) LIKE @Nome UPDATE hDados SET Nome = @Nome, Dados = @Dados, Observacoes = @Observacoes FROM hRequisicao hr, hDados hd WHERE hr.IdColaborador = @IdColaborador AND Nome LIKE @Nome AND IdStatus != 4 AND IdStatus != 5 ELSE INSERT INTO hDados(Nome,Dados,Observacoes,IdReq) VALUES ( @Nome, @Dados, @Observacoes, ( Select hr.IdReq From hRequisicao hr WHERE hr.IdColaborador = @IdColaborador AND IdStatus != 4 AND IdStatus != 5 ) ) END 处使用select命令检查从Application返回的参数是否在表hDados中存在,但这不起作用,因为它说返回的值大于1个值。如果没有这张支票,我应该怎么做?我尝试使用contains,但是我不知道如何在有条件的特定表中使用它

1 个答案:

答案 0 :(得分:2)

您的代码中有多个问题,难以正确回答您的问题。 我已经复制了代码,修改了我能做的,并在遇到问题时(即使我已解决问题)添加了注释。希望对您有所帮助。

-- I also don't like this condition, it indicates faulty design of the stored procedure
IF @Action = 'UPDATE' BEGIN 
    -- use Exists to solve the "subquery returned more than one result" problem
    IF EXISTS(
        Select 1
        From hDados hd 
        JOIN hRequisicao hr 
            ON hr.IdReq = hd.IdReq 
        WHERE hr.IdColaborador = 3 
        AND IdStatus != 4 
        AND IdStatus != 5
        AND Nome LIKE @Nome
        ) BEGIN
        UPDATE hDados -- use the alias you've used in the from clause
        SET Nome = @Nome, 
            Dados = @Dados, 
            Observacoes = @Observacoes
        -- From clause problem: You are creating a cross join between hRequisicao and hDados tables.
        -- use proper join syntax.
        FROM hRequisicao hr, hDados hd 
        WHERE hr.IdColaborador = @IdColaborador 
        AND Nome LIKE @Nome 
        AND IdStatus != 4 
        AND IdStatus != 5
    END
END ELSE BEGIN    
    -- You can't use a select statement inside the values clause. 
    /*
    INSERT INTO hDados(Nome,Dados,Observacoes,IdReq) 
    VALUES (
        @Nome,
        @Dados,
        @Observacoes,
        (
         Select 
        )
    )
   */
   -- Instead, use insert...select: (Note that this select statement might also return multiple rows!)
    INSERT INTO hDados(Nome,Dados,Observacoes,IdReq) 
    SELECT @Nome, @Dados, @Observacoes, hr.IdReq 
    FROM hRequisicao hr 
    WHERE hr.IdColaborador = @IdColaborador 
    AND IdStatus != 4 
    AND IdStatus != 5

END