在'之后删除所有内容,'或'。'在一个字符串 - SQL Server

时间:2015-09-16 15:45:10

标签: sql-server-2005

虽然我在StackOverflow上检查了答案,但我不确定将其应用于我的特定情况:

Size classes

问题是我得到的结果如下:

Select s.saleno, s.comments,
case 
    when Charindex('held by', s.comments) > 0 
    then substring(s.comments, Charindex('held by', s.comments)+8,40)
    else null end as TrimmedText,
FROMsales s
JOIN push p 
ON p.saleno = s.saleno
WHERE Charindex('held by', s.comments) > 0;

我需要的结果:

CompanyTwo, due ti
CompanyThreeee.
CompanyLong, is a scan 
CompanyShort, originally dated 01/01/2000
CompanyTTT.
CompanySomething, due 02/01/2010.

我一直想保持"公司[...]"直到它遇到一个点或逗号。此字符串后始终显示点或逗号。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

@Robert,你的评论明确表达了。你在这里:

将其粘贴到空查询窗口并执行。适应您的需求......

DECLARE @tbl TABLE(txt VARCHAR(100));
INSERT INTO @tbl VALUES
 ('CompanyTwo, due ti')
,('CompanyThreeee.')
,('CompanyLong, is a scan')
,('CompanyShort, originally dated 01/01/2000')
,('CompanyTTT.')
,('Company without something')
,('CompanySomething, due 02/01/2010.');

SELECT pos.*,pos2.*, LEFT(txt,(CASE WHEN pos2.Comma<pos2.Dot THEN pos2.Comma-1 ELSE pos2.Dot-1 END)) AS YourCompany
FROM @tbl AS t
CROSS APPLY
(SELECT ISNULL(CHARINDEX(',',t.txt),100000) AS Comma
       ,ISNULL(CHARINDEX('.',t.txt),100000) AS Dot
) AS pos
CROSS APPLY
(SELECT CASE WHEN pos.Comma=0 THEN 100000 ELSE pos.Comma END AS Comma
       ,CASE WHEN pos.Dot=0 THEN 100000 ELSE pos.Dot END AS Dot

) AS pos2