SQL:删除具有空值和空值的列

时间:2016-04-20 17:13:25

标签: sql-server

下面是我用来从两个不同的表中获取实体联系人姓名和地址信息的SQL查询。现在我试图排除既没有地址或名称信息的实体联系人,这些联系人将显示为空或空白。最后,我希望实体联系人有姓名或地址信息,或两者都有。

SELECT
    [FirstName]
   ,[MiddleName]
   ,[LastName]
   ,[DateOfBirth]
   ,[EntityAddress].[StreetNumber]
   ,[EntityAddress].[fk_Direction]
   ,[EntityAddress].[StreetName]
   ,[EntityAddress].[fk_StreetType]
   ,[EntityAddress].[Apartment]
   ,[EntityAddress].[city]
   ,[EntityAddress].[state]
   ,[EntityAddress].[zip]
   ,[EntityAddress].[country]
   ,[pk_entity]
FROM [entity]
Full Join [entityaddress]
On [entity].pk_entity=[entityaddress].fk_entity
Order by pk_entity desc

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT
    e.[FirstName]
   ,e.[MiddleName]
   ,e.[LastName]
   ,e.[DateOfBirth]
   ,[ea].[StreetNumber]
   ,[ea].[fk_Direction]
   ,[ea].[StreetName]
   ,[ea].[fk_StreetType]
   ,[ea].[Apartment]
   ,[ea].[city]
   ,[ea].[state]
   ,[ea].[zip]
   ,[ea].[country]
   ,e.[pk_entity]
FROM [entity] e
Full Join [entityaddress] ea
On [e].pk_entity=[ea].fk_entity
where (e.[LastName] is not null and [LastName]<>'') AND ([ea].[StreetName] is not null and [ea].[StreetName] <> '')
Order by pk_entity desc

答案 1 :(得分:0)

这应该有效。如 x&lt;&gt; &#39;&#39; 检查空字符串,如果值为NULL,则返回UNKNOWN而不是TRUE,因此您将是安全的。

SELECT
    [FirstName]
   ,[MiddleName]
   ,[LastName]
   ,[DateOfBirth]
   ,[EntityAddress].[StreetNumber]
   ,[EntityAddress].[fk_Direction]
   ,[EntityAddress].[StreetName]
   ,[EntityAddress].[fk_StreetType]
   ,[EntityAddress].[Apartment]
   ,[EntityAddress].[city]
   ,[EntityAddress].[state]
   ,[EntityAddress].[zip]
   ,[EntityAddress].[country]
   ,[pk_entity]
FROM [entity]
Full Join [entityaddress]
On [entity].pk_entity=[entityaddress].fk_entity
where (FirstName <> '') or (MiddleName <> '') or (LastName <> '') or ([entityaddress].[StreetName] <> '') 
Order by pk_entity desc

答案 2 :(得分:0)

我会试试这个:

SELECT
    e.[FirstName]
   ,e.[MiddleName]
   ,e.[LastName]
   ,e.[DateOfBirth]
   ,[ea].[StreetNumber]
   ,[ea].[fk_Direction]
   ,[ea].[StreetName]
   ,[ea].[fk_StreetType]
   ,[ea].[Apartment]
   ,[ea].[city]
   ,[ea].[state]
   ,[ea].[zip]
   ,[ea].[country]
   ,e.[pk_entity]
FROM [entity] e
Full Join [entityaddress] ea
On [e].pk_entity=[ea].fk_entity
where LEN(ISNULL(e.[LastName], '')) > 0 or LEN(ISNULL([ea].[StreetName], '')) > 0
Order by pk_entity desc

这样做,用空格替换NULL,然后执行LEN并查看它是否大于0.