SQL拆分字符串并获取NULL值而不是空字符串

时间:2019-01-29 13:54:49

标签: sql sql-server sql-server-2016

如何拆分字符串并获取NULL值而不是空字符串。

我对STRING_SPLITXML这两种方法特别感兴趣。 我希望这个查询:

SELECT * FROM STRING_SPLIT('a,b,,d', ',');

将在第三行NULL中返回,而不是返回空字符串。 有什么简单的方法可以实现它,即使用特殊字符吗?我的意思是:

SELECT * FROM STRING_SPLIT('a,b,[null],d', ',') -- this, of course, wouldn't go

我希望我可以使用XML方法从字符串中提取NULL:

CREATE FUNCTION dbo.SplitStrings_XML
(
   @List       varchar(8000),
   @Delimiter  char(1)
)
RETURNS TABLE WITH SCHEMABINDING
AS
   RETURN (SELECT [value] = y.i.value('(./text())[1]', 'varchar(8000)')
      FROM (SELECT x = CONVERT(XML, '<i>' 
          + REPLACE(@List, @Delimiter, '</i><i>') 
          + '</i>').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i));

从此处抓取的代码:https://sqlperformance.com/2016/03/t-sql-queries/string-split

2 个答案:

答案 0 :(得分:10)

NULLIF包装返回的值:

SELECT NULLIF([value],'') FROM STRING_SPLIT...

答案 1 :(得分:2)

据我所知,逗号之间的值实际上没有显示为空字符串。因此,您可以使用NULL表达式将空字符串替换为WITH cte AS ( SELECT * FROM STRING_SPLIT('a,b,,d', ',') ) SELECT value, CASE WHEN value = '' THEN NULL ELSE value END AS value_out FROM cte;

func FcmNewMessage(title, body, collapseKey, token string) *messaging.Message {
    oneHour := time.Duration(1) * time.Hour
    message := &messaging.Message{
        Notification: &messaging.Notification{
            Title: title,
            Body:  body,
        },
        Android: &messaging.AndroidConfig{
            TTL:         &oneHour,
            CollapseKey: collapseKey,
        },
        APNS: &messaging.APNSConfig{
            Headers: map[string]string{
                "apns-collapse-id": collapseKey,
            },
        },
        Webpush: &messaging.WebpushConfig{
            Notification: &messaging.WebpushNotification{
                Icon: "https://my-server/icon.png",
            },
            Headers: map[string]string{
                "urgency": "high",
                "topic":   collapseKey,
            },
        },
        Token: token,
    }
    return message
}