从开始和结束字符相同的字符串中检索文本

时间:2020-09-08 04:02:27

标签: sql sql-server

考虑到开始和结束是相同的字符串值,如何获得****星之间的文本?

Create Table #temp
(
    TestString varchar(400)
)

insert into #temp
(
    TestString
)
select
    '**** mary had a little lamb****'
union
select
    '**** humpy dumpty had a great fall**** All the king''s horses and all the king''s men'

1 个答案:

答案 0 :(得分:2)

您可以按如下方式使用基本字符串函数:

SELECT
    TestString,
    SUBSTRING(TestString,
              CHARINDEX('****', TestString) + 4,
              CHARINDEX('****', TestString, CHARINDEX('****', TestString) + 1) - 5) AS contents
FROM yourTable;

Demo

数据:

WITH yourTable AS (
    SELECT '**** mary had a little lamb****' AS TestString UNION ALL
    SELECT '**** humpy dumpty had a great fall**** All the king''s horses and all the king''s men'
)