我正在尝试检索此列值的第二个单词,但它显示为空白
我的疑问是:
select ltrim(
substring(companyname,
charindex(' ',companyname),
CHARINDEX(
' ',
ltrim(
SUBSTRING(
companyname,
charindex(' ',companyname),
LEN(companyname) - charindex(' ',companyname))
)
)
)
)
from pmweb_companies
where companyname = '7x24 Exchange'
结果应该返回:Exchange 但它显示空白。
答案 0 :(得分:0)
这是因为该查询要求总单词数超过两个,这意味着您要解析的字符串中至少需要两个空格。
如果你想要排除第一个单词并从第二个单词中获取任何内容,你可以使用类似的东西
select ltrim(
substring(
companyname,
charindex(' ', companyname),
len(companyname) - charindex(' ', companyname) + 1
)
);
如果您想完全改为第二个单词,可以将查询破解为
select ltrim(
substring(companyname,
charindex(' ', companyname),
CHARINDEX(
' ',
ltrim(
SUBSTRING(
companyname + ' fake',
charindex(' ', companyname),
LEN(companyname + ' fake') - charindex(' ', companyname))
)
)
)
)
from pmweb_companies
where companyname = '7x24 Exchange'
修改强>
如果我正确理解您的评论,如果字符串只有一个单词,则查询应返回空白。如果是这种情况,您可以在case
select
声明
select case
when charindex(
' ',
substring(
companyname,
charindex(' ', companyname),
LEN(companyname) - charindex(' ', companyname) + 1
)
) = 0 /* this means there's less than two words */
then '' /* you can place something else here, as you prefer */
else
ltrim(
substring(companyname,
charindex(' ', companyname),
CHARINDEX(
' ',
ltrim(
SUBSTRING(
companyname + ' fake',
charindex(' ', companyname),
LEN(companyname + ' fake') - charindex(' ', companyname))
)
)
)
)
end
from pmweb_companies
where companyname = '7x24 Exchange'