Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从特定字符中删除后续字符的SQL字符串_Sql_Sql Server - Fatal编程技术网

从特定字符中删除后续字符的SQL字符串

从特定字符中删除后续字符的SQL字符串,sql,sql-server,Sql,Sql Server,我被指派了一项任务来显示看起来像Foo-Bar,Foo-Bar,Foo-Bar,Foo…-Bar和我需要将其显示为仅Foo。这意味着我必须删除-符号后面的所有字符和它前面的所有特殊字符。有没有一个简单的函数可以满足我提供的所有字符串实例到所需的输出:Foo?我们使用SQLServer2008R2 编辑:我需要指出的是,Foo和Bar只是实际字符串的一种表示形式,因此硬编码字符串长度是行不通的 试试这个 declare @String varchar(20)='Foo!.,-Bar'

我被指派了一项任务来显示看起来像Foo-Bar,Foo-Bar,Foo-Bar,Foo…-Bar和我需要将其显示为仅Foo。这意味着我必须删除-符号后面的所有字符和它前面的所有特殊字符。有没有一个简单的函数可以满足我提供的所有字符串实例到所需的输出:Foo?我们使用SQLServer2008R2

编辑:我需要指出的是,Foo和Bar只是实际字符串的一种表示形式,因此硬编码字符串长度是行不通的

试试这个

   declare @String varchar(20)='Foo!.,-Bar'
   select substring(@String,charindex('F', @String),3)
返回

col                         Display
Foo - Bar                   Foo 
Foo-Bar                     Foo 
Foo        - Bar            Foo 
Foo!.,-Bar                  Foo 
Foo...-Bar                  Foo 
aaa Foo-Bar aaa             Foo 
There is no Bar-Foo here    There is no Bar-Foo here

感谢John Cappelletti提供的样本数据,我提出了这个问题,请您自己解决您未来的问题:

Declare @YourTable table (col varchar(50))
Insert into @YourTable values
 ('Foo - Bar')
,('Foo-Bar')
,('Foo        - Bar')
,('Foo!.,-Bar')
,('Foo...-Bar')
,('aaa Foo - Bar aaa')
查询:

SELECT  col, 
        LEFT(BeforeDash, LEN(BeforeDash) - PATINDEX('%[a-z]%', REVERSE(BeforeDash))+1)
FROM     
(
    SELECT col, LEFT(col, CHARINDEX('-', col)) As BeforeDash
    FROM @YourTable
) derived
结果:

col                     Display
Foo - Bar               Foo
Foo-Bar                 Foo
Foo        - Bar        Foo
Foo!.,-Bar              Foo
Foo...-Bar              Foo
aaa Foo - Bar aaa       aaa Foo

这是真的,只是文本长度是3。等等,它只适用于3个字母的单词,比如foo,如果第一个单词是3个或更多,甚至是2呢?like foot?@超级用户如果字符串以“foo”开头,我的第二个答案将给出结果,第一个答案将给出结果
SELECT  col, 
        LEFT(BeforeDash, LEN(BeforeDash) - PATINDEX('%[a-z]%', REVERSE(BeforeDash))+1)
FROM     
(
    SELECT col, LEFT(col, CHARINDEX('-', col)) As BeforeDash
    FROM @YourTable
) derived
col                     Display
Foo - Bar               Foo
Foo-Bar                 Foo
Foo        - Bar        Foo
Foo!.,-Bar              Foo
Foo...-Bar              Foo
aaa Foo - Bar aaa       aaa Foo