获取 SQL 中某个字符之前的所有内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35506851/
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
Get everything before a certain character in SQL
提问by thirty
I got the following entries in my database:
我的数据库中有以下条目:
E01234-1-1
E01234444-1-800000000
I want to trim the entry so I get:
我想修剪条目,所以我得到:
E01234-1
E01234444-1
So basically, I want everything before the second '-' regardless of the length
所以基本上,无论长度如何,我都希望在第二个“-”之前的所有内容
How can I solve it? Im using MS SQL SERVER 2012
我该如何解决?我使用的是 MS SQL SERVER 2012
I am using this but it only bring data from before first hyphen, not second hyphen
我正在使用它,但它只带来第一个连字符之前的数据,而不是第二个连字符
DECLARE @TABLE TABLE (STRING VARCHAR(100))
INSERT INTO @TABLE (STRING)
SELECT 'E01234-1-1'
UNION ALL SELECT 'E01234-1-200'
UNION ALL SELECT 'E01234-1-3000'
UNION ALL SELECT 'E01234-1-40000'
UNION ALL SELECT 'E01234-1-500000'
UNION ALL SELECT 'E01234-1-6000000'
UNION ALL SELECT 'E01234-1-70000000'
UNION ALL SELECT 'E01234444-1-800000000'
SELECT LEFT(STRING, CHARINDEX('-',STRING)-1) STRIPPED_STRING from @TABLE
RETURNS
E01234
E01234
E01234
E01234
E01234
E01234
E01234
E01234444
退货
E01234
E01234
E01234
E01234
E01234
E01234
E01234
E01234444
回答by Dan Field
If you need the second -
:
如果您需要第二个-
:
SELECT
LEFT(STRING, CHARINDEX('-', @test, CHARINDEX('-', @test) + 1) -1) STRIPPED_STRING
FROM @TABLE
Explanation: CHARINDEX
will get you the index of the -
- doing it twice (+ 1) specifies that the outter CHARINDEX
should start at the spot after the first -
in the string.
解释:CHARINDEX
将获得-
- 执行两次(+ 1)的索引,指定外部CHARINDEX
应从-
字符串中第一个之后的位置开始。
If you want to chop off everything after the last -
instead (regardless of whether it's second or not):
如果你想在最后一个之后砍掉所有东西-
(不管它是不是第二个):
SELECT
LEFT(STRING, LEN(STRING) - CHARINDEX('-', REVERSE(STRING))) STRIPPED_STRING
FROM @table
This time, you get the CHARINDEX
of the last (reverse the string) -
, and subtract that from the length of the whole string.
这一次,你得到CHARINDEX
最后一个(反转字符串)的-
,然后从整个字符串的长度中减去它。
回答by Jaydip Jadhav
Try this:
尝试这个:
DECLARE @STR NVARCHAR(MAX) = 'E01234444-1-800000000';
SELECT LEFT(@STR, CHARINDEX('-', @STR, CHARINDEX('-', @STR)) - 1)
回答by randomizer
If you are using MySQL use something like this:
如果您使用 MySQL,请使用以下内容:
SELECT SUBSTRING_INDEX(fieldname, '-', 2) FROM tablename