如何在SQL中用空字符串替换NULL?

时间:2014-01-20 11:57:06

标签: sql-server-2008

我使用以下查询以逗号分隔来获取列值。

    (SELECT STUFF ((SELECT  ',' + CAST(Proj_ID AS VARCHAR) FROM PROJECT
    left join dbo.PROJ_STA on
    Project.PROJ_STA_ID = Project.PROJ_STA_ID
    WHERE ENTER_DT < DATEADD(Year, -7, GETDATE())  AND PROJ_LFCYC_STA_CD = 'A' AND 
    PROJ_STA.PROJ_STA_DS = 'Cancelled' FOR XML PATH('')), 1, 1, '') 
    AS Enter_Date)  

任何人都可以指导我在这里用空字符串替换空值。

更新:

    (SELECT STUFF ((SELECT  ',' + coalesce( CAST(Proj_ID AS VARCHAR), '' ) FROM PROJECT
    left join dbo.PROJ_STA on
    Project.PROJ_STA_ID = Project.PROJ_STA_ID
    WHERE ENTER_DT < DATEADD(Year, -7, GETDATE())  AND PROJ_LFCYC_STA_CD = 'A' AND 
    PROJ_STA.PROJ_STA_DS = 'Cancelled' FOR XML PATH('')), 1, 1, '') 
    AS Enter_Date)  

3 个答案:

答案 0 :(得分:11)

尝试IsNull

select ISNULL(Column,'') as ColumnName

COALESCE

select COALESCE(NULLIF(ColumnName,''), 'Column')

答案 1 :(得分:3)

AdventureWorks数据库中的一个示例

select e.ModifiedDate, ISNULL(p.FirstName,'') as FirstName
from Person.BusinessEntity as e 
    left join Person.Person as p on e.BusinessEntityID = p.BusinessEntityID 

通过使用它,如果没有匹配的Person记录,FirstName将显示为空字符串而不是NULL

答案 2 :(得分:1)

您可以使用coalesce函数

将空值白化
select coalesce(MyColumn, '')

Coalesce接受任意数量的列或常量,并返回第一个非空的。

您的查询将是:

(SELECT STUFF ((SELECT  ',' + convert(varchar, coalesce( Proj_ID, '' )) FROM PROJECT
left join dbo.PROJ_STA on
Project.PROJ_STA_ID = Project.PROJ_STA_ID
WHERE ENTER_DT < DATEADD(Year, -7, GETDATE())  AND PROJ_LFCYC_STA_CD = 'A' AND 
PROJ_STA.PROJ_STA_DS = 'Cancelled' FOR XML PATH('')), 1, 1, '') 
AS Enter_Date)