简体   繁体   中英

How can I extract values from a string in SQL

My column has different length values and I want to extract all the values that are before the 2nd dash. Here are some of the values in the column

1AA-00001-20170101
AAAA-10010-20161201
1BBB2-22222-20151105

How do I get the following values in SQL

1AA-00001
AAAA-10010
1BBB2-22222

You could use:

SELECT LEFT(col, CHARINDEX( '-', col, CHARINDEX('-', col)+1)-1)
FROM table;

Rextester Demo

The structure of your strings seems pretty canonical. It seems you can do:

select left(col, len(col) - 9)

Another way

-- sample data
declare @table table (somestring varchar(100));
insert @table 
values ('1AA-00001-20170101'), ('AAAA-10010-20161201'),('1BBB2-22222-20151105');

-- solution
select somestring, newstring = 
         parsename(replace(somestring,'-','.'),3)+'-'+
         parsename(replace(somestring,'-','.'),2)
from @table;

Results

somestring            newstring
--------------------- ------------
1AA-00001-20170101    1AA-00001
AAAA-10010-20161201   AAAA-10010
1BBB2-22222-20151105  1BBB2-22222

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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