1

我需要在空格之前返回字符串中的所有内容:

select Substring('stack overflow', 1, CharIndex( ' ', 'stack overflow' ) - 1)

这将产生stack

但是,如果我们在数据中没有空格,我想返回整个字符串:

select Substring('stackoverflow', 1, CharIndex( ' ', 'stackoverflow' ) - 1)

我希望它回来stackoverflow

处理这种情况的正确方法是什么?

4

5 回答 5

5
;WITH T(C) AS
(
SELECT 'stack overflow' UNION ALL
SELECT 'stackoverflow'
)
SELECT LEFT(C, CharIndex( ' ', C + ' ' ) - 1)
FROM T
于 2012-07-19T16:48:55.933 回答
2

借用@MartinSmith 的定义:

;WITH T(C) AS
(
  SELECT 'stack overflow' 
  UNION ALL
  SELECT 'stackoverflow'
)
SELECT SUBSTRING(C, 1, COALESCE(NULLIF(CHARINDEX(' ', C)-1, -1), 255))
FROM T;

也就是说,我更喜欢马丁的。两者都避免检查长度或执行 CASE 等,但我假设您知道字符串的最大长度(这里我假设 255)。

于 2012-07-19T16:50:18.573 回答
2

我像往常一样迟到;在 SQL Fiddle 上

CREATE TABLE The_Table 
    (
     TestString varchar(50)
    );

INSERT INTO The_Table
(TestString)
VALUES
('stack overflow'),
('stackoverflow');


select 
[myResult] = case 
                when CharIndex( ' ', TestString)> 0 then Substring(TestString, 1, CharIndex( ' ', TestString ) - 1)
                when CharIndex( ' ', TestString)= 0 then TestString
                else TestString
             end
from The_Table
于 2012-07-19T17:46:44.530 回答
1
;With T(C) AS
(
    Select 'Stack'
    Union All
    Select 'Stack OverFlow' 
)
Select 
    Case When CharIndex(' ', C) > 0 
        Then SUBSTRING(C, 0, CharIndex(' ', C))
    Else
        C
    End
From T
于 2012-07-19T17:14:08.180 回答
1
Declare @str varchar(100)='stack overflow'
SELECT CASE WHEN CHARINDEX(' ',@str,1) > 0 then LEFT(@str,CHARINDEX(' ',@str,1)) else @str END
于 2012-07-20T05:48:01.390 回答