如何检查字段是否为空且空白?

时间:2017-09-01 08:44:12

标签: sql sql-server ssms

我正在尝试在为查找创建视图时,通过数据库中不存在的值来消除空格的可能性。我遇到的问题是,当我尝试检查CASE或空值时,我的NULL语句工作不正常。它似乎适用于那些空的但空白似乎没有那么多运气。在这种情况下,我试图检查importantField

的空值或空白
CREATE VIEW Lookup4 AS
SELECT TOP 140000 CONCAT(no,
    CASE WHEN (importantField is null OR importantField  = '') 
        THEN '' ELSE ' ' + importantField END, 
            fieldname + ' ', anotherField2)  AS UNRELATEDFIELD, Code, 
    CASE NAME
        WHEN '101,,,,,' THEN 'value1e'
        WHEN '14,,,,,' THEN 'value3'
        WHEN '16,,,,,' THEN 'value4'
    END AS NAME
FROM  dbo.Lookup

5 个答案:

答案 0 :(得分:1)

这就是你的目标

CREATE VIEW Lookup4 AS
SELECT TOP 140000 CONCAT(no,
    CASE WHEN (ISNULL(importantField,'') = '') 
        THEN '' ELSE ' ' + importantField END, 
            fieldname + ' ', anotherField2)  AS UNRELATEDFIELD, Code, 
    CASE NAME
        WHEN '101,,,,,' THEN 'value1e'
        WHEN '14,,,,,' THEN 'value3'
        WHEN '16,,,,,' THEN 'value4'
    END AS NAME
FROM  dbo.Lookup

答案 1 :(得分:0)

如果您只想检查null而不是空字符串,那么您也可以在尝试时使用ifnull。但这也不适合空字符串。

 SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1 
    from tablename

答案 2 :(得分:0)

尝试改变:

importantField is null

IsNull(importantField)

答案 3 :(得分:0)

CREATE VIEW Lookup4 AS
SELECT TOP 140000 CONCAT(no,ifnull(importantField,'')<>'', 
            fieldname + ' ', anotherField2)  AS UNRELATEDFIELD, Code, 
    CASE NAME
        WHEN '101,,,,,' THEN 'value1e'
        WHEN '14,,,,,' THEN 'value3'
        WHEN '16,,,,,' THEN 'value4'
    END AS NAME
FROM  dbo.Lookup

答案 4 :(得分:0)

根据您的结果进行细微更改

方法1:

 Select *
    From dbo.Lookup
    Where IsNull(importantField, '') = ''

方法2:

 Select *
    From dbo.Lookup
    Where (importantField is NULL or importantField = '')