【问题标题】:Parsing a text from one column to three columns in SQL Server Select Query在 SQL Server Select Query 中将文本从一列解析为三列
【发布时间】:2020-05-04 16:55:42
【问题描述】:

我有一个表格,我需要从中解析一个包含句子的列(即关于问题的 Q 和 A),我想将该列解析为 3 列,请参见下面的示例。

在此先感谢:-)

问候, 哈菲兹

【问题讨论】:

  • 你自己尝试过什么?提示,查找 CHARINDEX, SUBSTRING
  • 当然@JonathanWillcock 会尝试并发布它..

标签: sql sql-server text-parsing string-parsing


【解决方案1】:

根据SUBSTRING, PATHINDEX or CHARINDEX的更简单的方法

DECLARE @Text VARCHAR(MAX) = '<Date & Time Stamp>- User 1. What has caused the issue ? There was a script which mistakenly included and executed during deployment which caused
loutage 2. How was the issue resolved ? The Negative Impact was resolved by reverting back the
I changes which were deployed and getting back to the previous state.
3. What action are being taken to ensure similar negative impact will not occur again in future ?
Considering a humar error, scripts are being reviewed more diligently over the future release and
we have advised developments teams to keep a track of what is being pushed to make sure it does
'

DECLARE @RevisedText VARCHAR(MAX) = @Text
SET @RevisedText = REPLACE(@RevisedText, '<Date & Time Stamp>- User 1. What has caused the issue ?', '|{1}')
SET @RevisedText = REPLACE(@RevisedText, '2. How was the issue resolved ?', '|{2}')
SET @RevisedText = REPLACE(@RevisedText, '3. What action are being taken to ensure similar negative impact will not occur again in future ?', '|{3}')

SELECT
    Col_1 = (SELECT LTRIM(RTRIM(REPLACE(value, '{1}', ''))) FROM string_split(@RevisedText, '|') WHERE value LIKE '{1}%'),
    Col_2 = (SELECT LTRIM(RTRIM(REPLACE(value, '{2}', ''))) FROM string_split(@RevisedText, '|') WHERE value LIKE '{2}%'),
    Col_3 = (SELECT LTRIM(RTRIM(REPLACE(value, '{3}', ''))) FROM string_split(@RevisedText, '|') WHERE value LIKE '{3}%')

注意:如果您的 SQL Server 兼容级别低于 130,则可以使用 UDF 而不是本机 split_string

CREATE FUNCTION string_split (
      @String       NVARCHAR(MAX)
    , @Delimiter    CHAR(1)
)
RETURNS @Table TABLE (StrCol    NVARCHAR(MAX))

AS      
BEGIN   
    DECLARE @Delimiter1 CHAR(3) = '%' + @Delimiter + '%'
    WHILE PATINDEX(@Delimiter1 , @String) <> 0  
    BEGIN
        INSERT INTO @Table VALUES ( LEFT(@String,PATINDEX(@Delimiter1 , @String)-1) )
        SET @String =  STUFF(@String, 1, PATINDEX(@Delimiter1 , @String), '')       
    END
    INSERT INTO @Table VALUES (@String )

    RETURN
END  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多