我的SQL Server子查询始终返回NULL

时间:2015-12-02 03:36:20

标签: sql-server null subquery

我有一个表“Representantes”,其字段为“Allow Nulls”,名为“Complemento”。 问题是当“Complemento”为null或为空时子查询总是返回null但是当“Complemento”具有任何值时,子查询完美地工作。

看看我的代码。

请。

`USE [Realb_DB]
GO
/****** Object:  StoredProcedure [dbo].[CadastrarRepresentante]    Script Date: 01/12/2015 19:54:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[CadastrarRepresentante]
    @RazaoSocial nvarchar(100),
    @Nome_Fantasia nvarchar(100),
    @CNPJ nvarchar(50), 
    @Gestor_Responsavel nvarchar(100),
    @RG_Gestor nvarchar(25),
    @CPF_Gestor nvarchar(25),

    @Logradouro nvarchar(100),
    @Bairro nvarchar(100),
    @Numero nvarchar(100),
    @Complemento nvarchar(100) = null,
    @Municipio nvarchar(100),
    @Estado nvarchar(100)
AS
BEGIN

EXEC dbo.cadastrarEndereco @Logradouro = @Logradouro , @Bairro = @Bairro , @Numero = @Numero , 
@Complemento = @Complemento , @Municipio = @Municipio , @Estado = @Estado ;

        WITH CTE_ENDERECO2(ID_Endereco)
        AS (SELECT TOP 1 ID_Endereco FROM dbo.Tabela_Endereco 
        WHERE Logradouro = @Logradouro AND Bairro = @Bairro AND Numero = @Numero
        AND Complemento = @Complemento AND Municipio = @Municipio AND Estado = @Estado ) 

        INSERT INTO Tabela_Representante(Razao_Social, Nome_Fantasia, CNPJ, Gestor_Responsavel, RG_Gestor, CPF_Gestor, FK_Endereco) VALUES(@RazaoSocial,@Nome_Fantasia,@CNPJ,@Gestor_Responsavel,@RG_Gestor,@CPF_Gestor,(SELECT ID_Endereco FROM CTE_ENDERECO2)) 

END`

错误讯息。

enter image description here

我该如何解决?

2 个答案:

答案 0 :(得分:0)

您可以根据子查询的要求使用以下任何一项:

选项1 :使用IFNULL并使用0或任何其他数字(如果为null)进行比较。

SELECT TOP 1 ID_Endereco FROM dbo.Tabela_Endereco 
        WHERE Logradouro = @Logradouro AND Bairro = @Bairro AND Numero = @Numero
        AND IFNULL(Complemento, 0) = @Complemento AND Municipio = @Municipio AND Estado = @Estado 

选项2:在此列中添加对NULL值的额外检查

SELECT TOP 1 ID_Endereco FROM dbo.Tabela_Endereco 
        WHERE Logradouro = @Logradouro AND Bairro = @Bairro AND Numero = @Numero
        AND (Complemento = @Complemento OR Complemento is null) AND Municipio = @Municipio AND Estado = @Estado 

答案 1 :(得分:0)

我认为你应该用于 SQL:ISNULL(COLUMN_NAME, VALUE) 并且用于 MYSQL:IFNULL(COLUMN_NAME, VALUE) 如果您将空值作为参数传递给此过程。因此,它会检查列中是否有空白,它会将其转换为空白。

在您的情况下尝试这样

(SELECT TOP 1 ID_Endereco FROM dbo.Tabela_Endereco 
        WHERE Logradouro = @Logradouro AND Bairro = @Bairro AND Numero = @Numero
        AND IFNULL(Complemento, '') = @Complemento AND Municipio = @Municipio AND Estado = @Estado )