2011-03-28 95 views
28

我想筛选记录筛选....SQL查询 - 如何用null或not null

如果statusid为null,过滤记录(其中statusId不为null)

如果statusid是not null,过滤statusid等于指定的statusid的记录。

我该怎么做?

回答

45

就像你说的

select * from tbl where statusid is null 

select * from tbl where statusid is not null 

如果您statusid不为空,那么它将被选择就好了,当你有一个实际值,不需要任何“如果“如果这逻辑是什么,你在想

select * from tbl where statusid = 123 -- the record(s) returned will not have null statusid 

,如果你想选择它为空或值,尝试

select * from tbl where statusid = 123 or statusid is null 
+0

但你怎么做“如果”? – 001 2011-03-28 03:30:50

+0

看到我的最后加入,其中包含“或” – JeremyWeir 2011-03-28 03:33:58

+0

谢谢,它现在的作品:) – 001 2011-03-28 03:47:39

3

statusid = statusid怎么样?空不等于null。

0

我觉得这可能是工作:

select * from tbl where statusid = isnull(@statusid,statusid) 
1
WHERE something IS NULL 

WHERE something IS NOT NULL 
1

SET ANSI_NULLS关闭 去 SELECT * FROM表t 内部O上t.statusid加入otherTable = O .statusid go set ansi_nulls on go

0

无论你尝试检查一个列的NULL值,你应该使用

IS NULLIS NOT NULL

你不应该使用= NULL或== NULL


实施例(NULL)

select * from user_registration where registered_time IS NULL 

将与返回行值是NULL


(NOT NULL)

select * from user_registration where registered_time IS NOT NULL 

将与registered_time值返回行是NOT NULL

注:关键字nullnot nullisnot case sensitive