我需要在空格之前返回字符串中的所有内容:
select Substring('stack overflow', 1, CharIndex( ' ', 'stack overflow' ) - 1)
这将产生stack
但是如果我们在数据中没有空格,我想返回整个字符串:
select Substring('stackoverflow', 1, CharIndex( ' ', 'stackoverflow' ) - 1)
我希望返回stackoverflow
处理这种情况的正确方法是什么?
答案 0 :(得分:5)
;WITH T(C) AS
(
SELECT 'stack overflow' UNION ALL
SELECT 'stackoverflow'
)
SELECT LEFT(C, CharIndex( ' ', C + ' ' ) - 1)
FROM T
答案 1 :(得分: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)。
答案 2 :(得分:2)
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
答案 3 :(得分: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
答案 4 :(得分:1)
Declare @str varchar(100)='stack overflow'
SELECT CASE WHEN CHARINDEX(' ',@str,1) > 0 then LEFT(@str,CHARINDEX(' ',@str,1)) else @str END