我们的数据库中有一个地址字段,我需要将其分成两列(Address1和Address2)。我正在寻找一种在CR / LF部分之后拆分此字符串的方法。
我该怎么做?我正在使用SSMS 2016
答案 0 :(得分:1)
可以使用这样的东西 -
回车符是char(13)
DECLARE @Str table (str VARCHAR(100))
insert into @Str values
('Test
Word'),
('NoCRLF')
SELECT CASE WHEN CHARINDEX(CHAR(13), Str ) > 0 THEN SUBSTRING(Str , 1, CHARINDEX(CHAR(13), Str ) - 1) ELSE Str END AS [First],
CASE WHEN CHARINDEX(CHAR(13), Str ) > 0 THEN SUBSTRING(Str , CHARINDEX(CHAR(13), Str ) + 1, LEN(Str )) ELSE NULL END AS [Last]
FROM @Str
答案 1 :(得分:1)
CHARINDEX
查找您的地址是否有新的换行符。并基于此,您可以使用SUBSTRING
分割您的地址。CHAR(13)
的情况一样,你将只获得Address1而地址2将是NULL
。如果Address为NULL
或空格,它将处理它。 以下是示例代码:
DECLARE @AddressTable AS TABLE
(
Address nvarchar(MAX) NULL,
Address1 nvarchar(MAX) NULL,
Address2 nvarchar(MAX) NULL
)
INSERT @AddressTable (Address)
SELECT '1600 Pennsylvania Avenue' + CHAR(13) + 'Washington DC ' Address UNION ALL
SELECT '221 B Baker St, London, England' Address UNION ALL
SELECT NULL Address UNION ALL
SELECT '' Address UNION ALL
SELECT '11 Wall Street' + CHAR(13) + 'New York, NY' Address
SELECT
CASE
WHEN CHARINDEX(CHAR(13), Address) > 0 THEN SUBSTRING(Address, 1, CHARINDEX(CHAR(13), Address) - 1) + '|'
ELSE Address END
Address1,
CASE
WHEN CHARINDEX(CHAR(13), Address) > 0 THEN SUBSTRING(Address, CHARINDEX(CHAR(13), Address) + 1, LEN(Address)) + '|'
ELSE NULL END
Address2
FROM @AddressTable
答案 2 :(得分:0)
从SQL Server 2016开始,有一个string_split函数:
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql