SQL Server:NOT IN in where子句不使用NVARCHAR

时间:2017-01-31 11:30:40

标签: sql-server sql-server-2008 sql-server-2008-r2 notin

我有下表:

DECLARE @P AS TABLE
(
    ID int,
    PID  int,
    PNAME NVARCHAR(30),
    PARENT_PNAME NVARCHAR(30),
    Error int
)

INSERT INTO @P VALUES
(554,1,'AAAA',NULL,0),
(554,2,'BBBB',NULL,0),
(554,3,'CCCC',NULL,0),
(554,4,'DDDD','AAAA',0),
(554,5,'EEEE','AAAA',0),
(554,6,'FFFF',NULL,0),
(554,7,'GGGG',NULL,0),
(554,8,'HHHH',NULL,0),
(554,9,'IIII',NULL,0),
(554,10,'JJJJ',NULL,0),
(554,11,'KKKK',NULL,0);

如果我在查询下面运行:

select ID, PID, PNAME, PARENT_PNAME,  Error
from   @P                  
where  PNAME not in (select PARENT_PNAME 
                     from   @P
                     where  PNAME is not null)
       AND PARENT_PNAME IS NOT NULL

我什么都没得到,没有结果。为什么" NOT IN"不工作?

我需要获得以下两行:

(554,4,'DDDD','AAAA',0)
(554,5,'EEEE','AAAA',0)

5 个答案:

答案 0 :(得分:4)

DECLARE @P AS TABLE
(
    ID int,
    PID  int,
    PNAME NVARCHAR(30),
    PARENT_PNAME NVARCHAR(30),
    Error int
)

INSERT INTO @P VALUES
(554,1,'AAAA',NULL,0),
(554,2,'BBBB',NULL,0),
(554,3,'CCCC',NULL,0),
(554,4,'DDDD','AAAA',0),
(554,5,'EEEE','AAAA',0),
(554,6,'FFFF',NULL,0),
(554,7,'GGGG',NULL,0),
(554,8,'HHHH',NULL,0),
(554,9,'IIII',NULL,0),
(554,10,'JJJJ',NULL,0),
(554,11,'KKKK',NULL,0);

select * from @P where PARENT_PNAME is not null

输出

ID  PID PNAME   PARENT_PNAME    Error
554 4   DDDD    AAAA    0
554 5   EEEE    AAAA    0

答案 1 :(得分:1)

您还应该在嵌套查询中添加and PARENT_PNAME is not null

SELECT ID, PID, PNAME, PARENT_PNAME, Error
FROM @P
WHERE PNAME NOT IN (
        SELECT PARENT_PNAME
        FROM @P
        WHERE PNAME IS NOT NULL
            AND PARENT_PNAME IS NOT NULL
        )
    AND PARENT_PNAME IS NOT NULL

这就是为什么你没有得到任何结果的原因。

more detailed information have a look here

答案 2 :(得分:1)

您不需要NOT IN条款。试试吧:

SELECT * FROM  @P where PARENT_PNAME is NOT NULL

答案 3 :(得分:0)

select ID, PID, PNAME, PARENT_PNAME,  Error
from   @P                  
where  PNAME<>PARENT_PNAME
       AND PARENT_PNAME IS NOT NULL

如果您有空值,请不要使用NotIN进行比较,请使用NOT Exists

答案 4 :(得分:0)

有很多方法可以得到所需的结果。

--method 1    
select ID, PID, PNAME, PARENT_PNAME,  Error
from   @P P1                 
where EXISTS (select PARENT_PNAME 
                 from   @P P2
                 where  p2.PNAME = p1.PNAME 
                        and P1.PARENT_PNAME is not null)

--query 2
select P1.* 
from @P  P1
where P1.PARENT_PNAME is not null