Select column, if blank select from another

柔情痞子 提交于 2019-12-18 10:48:28

问题


How does one detect whether a field is blank (not null) and then select another field if it is?

What I really need is a IsBlank function that works the same as IsNull but with with blanks.

REPLACE doesn't work with blanks, COALESCE only works with NULLS.


回答1:


How about combining COALESCE and NULLIF.

SELECT COALESCE(NULLIF(SomeColumn,''), ReplacementColumn)
FROM SomeTable



回答2:


You can use a CASE statement for this

select 
Case WHEN Column1 = '' OR Column1 IS NULL OR LEN (TRIM (Column1))  = 0 
     THEN Column2 
     ELSE Column1 END as ColumnName
from TableName



回答3:


EDIT: You can't use IF() in mssql.

Use an IF statement in the SELECT portion of your SQL:

SELECT IF(field1 != '', field1, field2) AS myfield FROM ...



回答4:


You could always write an isBlank() function, something like

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION isBlank
(
    @CheckExpression varchar, @ReplacementExpression varchar
)
RETURNS varchar
AS
BEGIN
    IF @CheckExpression IS NOT NULL
    BEGIN
        IF @CheckExpression='' or LEN(@CheckExpression) = 0
        RETURN @ReplacementExpression
    ELSE
        RETURN @CheckExpression
    END

    RETURN @ReplacementExpression
END
GO


来源:https://stackoverflow.com/questions/1747750/select-column-if-blank-select-from-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!