修剪 SQL 中字符串的开头和结尾

Trimming the beginning and end of string in SQL

我有一个很长的字符串,我想要 trim 的开头和结尾。请参阅下面的随机示例:

{ "topic": "birds", "body":"cool bird", "attachment1":"bird1", "attachment2":"anotherbird" }

我想要的输出:

"attachment1":"bird1", "attachment2":"anotherbird"

我想保留附件,所以我必须 trim 第一个附件“attachment1”之前的所有内容,并删除“}”以及额外的 space。

仅供参考-我正在使用 SQL 服务器。任何反馈或建议都会非常有帮助!谢谢你。 :)

编辑:如果在字符串中找不到'"attachment1":',我希望值为return NULL 而不是returning 原始字符串。我将如何修改答案以纳入此规则?

您可以使用:

select replace(stuff(str, 1, charindex('"attachment1":', str), ''), ' }', '')

Here 是一个 db<>fiddle.

编辑:

可能处理缺失 "attachment" 的最简单解决方案是使用 case:

select (case when str like '%"attachment1"%' 
             then replace(stuff(str, 1, charindex('"attachment1":', str), ''), ' }', '')
        end)

在 SQL Server 2016 及更高版本中使用 JSON API。

STRING_AGG() 功能在 SQL Server 2017 及更高版本中可用。

这种方法的美妙之处在于“附件%”key/value对可以在任何位置。

SQL

DECLARE @JSON NVARCHAR(MAX) = N'{ "topic": "birds", "body":"cool bird", "attachment1":"bird1", "attachment2":"anotherbird" }';

;WITH rs AS
(
    SELECT [key], [value]
    FROM OPENJSON(@JSON)
)
SELECT STRING_AGG(FORMATMESSAGE('"%s":"%s"', [key], [value]), ',') AS Result
FROM rs
WHERE rs.[key] LIKE 'attachment%';

输出

+----------------------------------------------------+
|                       Result                       |
+----------------------------------------------------+
| "attachment1":"bird1","attachment2":"anotherbird"  |
+----------------------------------------------------+