简体   繁体   English

在SQL字符串中寻找特定的子字符串

[英]Looking for a particular substring in SQL string

I'm trying to find some SQL code and having it doesn't seem to be returning my desired output. 我试图找到一些SQL代码,但似乎没有返回我想要的输出。

Here is my create/insert statement 这是我的创建/插入语句

CREATE TABLE temp
    ([screenName] varchar(130), [realName] varchar(57))
;

INSERT INTO temp
    ([screenName], [realName])
VALUES
    ('WillyWonka', 'Will Stinson'),
    ('Barbara Smith', 'Barbara Smith'),
    ('JoanOfArc', 'JoanArcadia'),
    ('LisaD', 'Lisa Diddle')
;

What i'm looking for is the rows where the realName column has a space in it ... such as the first two and the fourth line ... and the realName the second word after the space Starts with the letter 'S' and is then followed by any character and then has the letter i, followed by any series of characters. 我正在寻找的是realName列中有空格的行...例如前两行和第四行...而realName则是空格后的第二个单词,以字母'S'开头,然后是任何字符,然后是字母i,然后是任何一系列字符。 This is where i'm stuck. 这就是我卡住的地方。

  SELECT LEFT(realName,CHARINDEX(' ',realName)-1)
  FROM
  temp
  Where LEFT(realName,CHARINDEX(' ',realName)-1) like 'S%'

although i'm pretty sure what i'm doing there is wrong but can't figure out how to make it correct. 尽管我很确定自己在做什么,但我不知道该怎么做才能正确。

apologies to the changes -- but how would i change the code if the name were to change and possibly have multiple space ( Jimmy Dean Stinson ) If I wanted to modify it to look from the right? 对所做的更改表示歉意,但是如果要更改名称并且可能有多个空格,我将如何更改代码( Jimmy Dean Stinson )如果我想对其进行修改以使其从右边看?

Thank you. 谢谢。

Use LIKE operator. 使用LIKE运算子。

SELECT *
FROM   temp
WHERE  realName LIKE '% S_i%' 

do you want 你想要

 SELECT LEFT(realName,CHARINDEX(' ',realName)-1)
  FROM
  temp
  Where realName like '% S_i%'

wildcard single character 通配符单个字符

Second word of the name where it starts with s followed by another character followed by i followed by any number of characters: 名称的第二个单词,以s开头,后跟另一个字符,后跟i后跟任意数量的字符:

 SELECT LEFT(realName,CHARINDEX(' ',realName)-1)
  FROM
  temp
  Where LEFT(realName,CHARINDEX(' ',realName)-1) like 'S_i%'

The underscore character _ is a wild card for any single character. 下划线字符_是任何单个字符的通配符。

You can find more wildcard characters for use with LIKE Here 您可以在此处找到更多与LIKE一起使用的通配符

You can do this to avoid the indexing error. 您可以这样做以避免索引错误。 That is happening on the values where there is no space. 这是在没有空间的值上发生的。 I added % to the like string which will ensure that the name has anything followed by a space, followed by your condition. 我在类似的字符串中添加了%以确保名称中没有空格,后跟空格,再加上您的条件。

 SELECT LEFT(realName,CHARINDEX(' ',realName)-1)
  FROM
  temp
  Where realName like '% S_i%'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM