在SQL Server中,获取每一行两个“-”之间的文本。

huangapple go评论127阅读模式
英文:

Get the text between two "-"s for each row in SQL Server

问题

请帮助我在SQL Server中剪裁下面的示例文本。我想要获取两个 '-' 之间的数据(某些行没有 '-')。

期望的输出是:

AB DCE
AB DCE
ABC
AB DCE
ABC

我尝试了:

select substring(mycol, 4, charindex('-', mycol, 12))

但结果不准确。

英文:

Can someone please help me with trimming the below sample texts in SQL Server? I am looking to get the data between the two '-' (some rows do not have a '-').

AB DCE
CM-AB DCE  -228
ABC
CM-AB DCE-214
CJ-ABC-228

The output expected is:

AB DCE
AB DCE
ABC
AB DCE
ABC

I tried:

select substring(mycol, 4, charindex('-', mycol, 12) ) 

But the results are not accurate.

答案1

得分: 0

以下是翻译好的部分:

如果您使用 CHARINDEX 收集第一个符号的位置和第二个符号的位置,您可以使用 SUBSTRING 提取它们之间的内容。

WITH cte AS (
    SELECT *, 
           CHARINDEX('-', txt)                        AS startidx,
           CHARINDEX('-', txt, CHARINDEX('-', txt)+1) AS endidx
    FROM tab
)
SELECT SUBSTRING(txt, 
                 CASE WHEN startidx > 0 THEN startidx+1 ELSE 0 END,
                 CASE WHEN startidx > 0 THEN endidx-startidx-1 ELSE LEN(txt) END) AS txt
FROM cte

输出

txt
AB DC
AB DCE
AB
AB DCE
ABC

在此查看演示链接

英文:

If you gather the position of your first symbol, and the position of your second symbol with CHARINDEX, you can extract what's contained inbetween with SUBSTRING.

WITH cte AS (
    SELECT *, 
           CHARINDEX('-', txt)                        AS startidx,
           CHARINDEX('-', txt, CHARINDEX('-', txt)+1) AS endidx
    FROM tab
)
SELECT SUBSTRING(txt, 
                 CASE WHEN startidx > 0 THEN startidx+1 ELSE 0 END,
                 CASE WHEN startidx > 0 THEN endidx-startidx-1 ELSE LEN(txt) END) AS txt
FROM cte

Output:

txt
AB DC
AB DCE
AB
AB DCE
ABC

Check the demo here.

答案2

得分: 0

以下是您要翻译的内容:

"seems like the question has been answered here

https://www.webcodeexpert.com/2016/08/sql-server-query-to-get-string-between.html

SELECT SUBSTRING(txt,CHARINDEX('-',txt)+1,
(((LEN(txt))-CHARINDEX('-',REVERSE(txt)))-CHARINDEX('-',txt)))
AS Result FROM tab"

英文:

seems like the question has been answered here

https://www.webcodeexpert.com/2016/08/sql-server-query-to-get-string-between.html

SELECT SUBSTRING(txt,CHARINDEX('-',txt)+1,
(((LEN(txt))-CHARINDEX('-',REVERSE(txt)))-CHARINDEX('-',txt)))
AS Result FROM tab

huangapple
  • 本文由 发表于 2023年5月24日 21:23:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324037.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定