SQL 从SQL中的字符串中提取第一个单词,其中字符串是单个单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28903230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 03:23:59  来源:igfitidea点击:

Extracting first word from a string in SQL, where the string is a single word

sqlsubstringansi-sql

提问by hassapikos

I am able to extract the first word from a string, using ANSI SQL, like this:

我能够使用 ANSI SQL 从字符串中提取第一个单词,如下所示:

SELECT SUBSTRING(name FROM 1 FOR POSITION(' ' IN name)) AS first_name

However, if the original string is only one word long (ie, if there is no space), it returns an empty substring.

但是,如果原始字符串只有一个字长(即,如果没有空格),则返回一个空子字符串。

How can the above query be adapted to solve this problem?

如何调整上述查询来解决这个问题?

Thanks in advance.

提前致谢。

回答by rghome

Simply but messy solution - add a space on the end:

简单但凌乱的解决方案 - 在末尾添加一个空格:

SELECT SUBSTRING((name || ' ') FROM 1 FOR POSITION(' ' IN (name || ' '))) AS first_name

回答by Parfait

Use a conditional if statement.

使用条件 if 语句。

For a MySQL/SQL Server answer:

对于 MySQL/SQL Server 答案:

SELECT IF(INSTR(name, ' ') >0, LEFT(name, INSTR(name, ' ') - 1), name) AS firstname

For Oracle:

对于甲骨文:

SELECT IF(INSTRB(name, ' ', 1, 1) >0, SUBSTR(name, 1, INSTRB(name, ' ', 1, 1) - 1), name) AS firstname

回答by Stephan

Put Column Name in place of @foo

用列名代替@foo

DECLARE @Foo VARCHAR(50) = 'One Two Three'

SELECT 
CASE
--For One Word
WHEN CHARINDEX(' ', @Foo, 1) = 0 THEN @Foo

--For multi word
ELSE SUBSTRING(@Foo, 1, CHARINDEX(' ', @Foo, 1) - 1)

END

回答by pushp

    DECLARE @test VARCHAR(50) = 'One Two Three'

SELECT SUBSTRING(LTRIM(@test),1,(CHARINDEX(' ',LTRIM(@test) + ' ')-1))

SELECT SUBSTRING(LTRIM(@test),1,(CHARINDEX(' ',LTRIM(@test) + ' ')-1))

回答by jhilden

I'm sure there is a cleaner way to do it, but this works.

我确信有一种更清洁的方法可以做到这一点,但这是有效的。

DECLARE @tbl TABLE (i varchar(100));

INSERT INTO @tbl ( i )
VALUES  ('hello'), ('hello space here');

SELECT *, 
    SUBSTRING(i, 0, CASE CHARINDEX(' ', i)
        WHEN 0 THEN LEN(i) + 1
        ELSE CHARINDEX(' ', i)
    END)
FROM @tbl