SQL 选择列,如果空白从另一个选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1747750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select column, if blank select from another
提问by graham.reeds
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.
我真正需要的是一个 IsBlank 函数,它的工作原理与 IsNull 相同,但带有空格。
REPLACE doesn't work with blanks, COALESCE only works with NULLS.
REPLACE 不适用于空白,COALESCE 仅适用于 NULL。
回答by PHeiberg
How about combining COALESCE and NULLIF.
结合 COALESCE 和 NULLIF 怎么样。
SELECT COALESCE(NULLIF(SomeColumn,''), ReplacementColumn)
FROM SomeTable
回答by Raj More
You can use a CASE
statement for this
您可以CASE
为此使用声明
select
Case WHEN Column1 = '' OR Column1 IS NULL OR LEN (TRIM (Column1)) = 0
THEN Column2
ELSE Column1 END as ColumnName
from TableName
回答by MDCore
EDIT: You can't use IF()
in mssql.
编辑:您不能IF()
在 mssql 中使用。
Use an IF statement in the SELECT portion of your SQL:
在 SQL 的 SELECT 部分使用 IF 语句:
SELECT IF(field1 != '', field1, field2) AS myfield FROM ...
回答by Chris Welsh
You could always write an isBlank() function, something like
你总是可以写一个 isBlank() 函数,比如
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