如何仅选择出现在 SQL Select 语句中特定符号之前的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8299176/
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
How to select only the characters appearing before a specific symbol in a SQL Select statement
提问by some_bloody_fool
I have strings in a database like this:
我在数据库中有这样的字符串:
[email protected]/IMCLientName
And I only need the characters that appear before the @ symbol.
而且我只需要出现在@ 符号之前的字符。
I am trying to find a simple way to do this in SQL.
我试图在 SQL 中找到一种简单的方法来做到这一点。
回答by Ian Nelson
DECLARE @email VARCHAR(100)
SET @email = '[email protected]/IMCLientName'
SELECT SUBSTRING(@email,0, CHARINDEX('@',@email))
回答by Izulien
Building on Ian Nelson's example we could add a quick check so we return the initial value if we don't find our index.
以Ian Nelson的示例为基础,我们可以添加一个快速检查,以便在找不到索引时返回初始值。
DECLARE @email VARCHAR(100)
SET @email = 'firstname.lastname.email.com/IMCLientName'
SELECT CASE WHEN CHARINDEX('@',@email) > 0
THEN SUBSTRING(@email,0, CHARINDEX('@',@email))
ELSE @email
END AS email
This would return 'firstname.lastname.email.com/IMCLientName'. If you used '[email protected]/IMCLientName' then you would receive 'firstname.lastname' as a result.
这将返回“firstname.lastname.email.com/IMCLientName”。如果您使用了“[email protected]/IMCLientName”,那么您将收到“firstname.lastname”作为结果。