简体   繁体   中英

Extract characters after a symbol in sql server 2012

I have a table List shown below:

+------+-------------------------------------+
| Code |                name                 |
+------+-------------------------------------+
| A001 | ABBOTT_1000000                      |
| A002 | AGCO_1000001                        |
| A003 | ALFA LAVAL_1000002                  |
| A004 | ALSTOM POWER INDIA LIMITED_1000003  |
| A005 | AMERICAN BUREAU OF SHIPPING_1000004 |
+------+-------------------------------------+

I need to update the table extracting the characters present after _ in name and replace them in code column. like this.

+---------+-------------------------------------+
|  Code   |                name                 |
+---------+-------------------------------------+
| 1000000 | ABBOTT_1000000                      |
| 1000001 | AGCO_1000001                        |
| 1000002 | ALFA LAVAL_1000002                  |
| 1000003 | ALSTOM POWER INDIA LIMITED_1000003  |
| 1000004 | AMERICAN BUREAU OF SHIPPING_1000004 |
+---------+-------------------------------------+

This is has to be done in sql server 2012. please help me.

Try this

with cte as
(
select substring(name,charindex('_',name)+1,len(name)) as ext_str,*
from yourtable
)
update cte set code = ext_str

You can try to use SUBSTRING in following:

SAMPLE DATA

CREATE TABLE #MyTable
(
Code NVARCHAR(60),
Name NVARCHAR(60)
)
INSERT INTO #MyTable VALUES
('A001','ABBOTT_1000000'                      ),
('A002','AGCO_1000001'                        ),
('A003','ALFA LAVAL_1000002'                  ),
('A004','ALSTOM POWER INDIA LIMITED_1000003'  ),
('A005','AMERICAN BUREAU OF SHIPPING_1000004' )

QUERY

UPDATE #MyTable
SET Code = SUBSTRING(Name, CHARINDEX('_', Name) + 1, LEN(Name))

TESTING

SELECT * FROM #MyTable    
DROP TABLE #MyTable

OUTPUT

Code    Name
1000000 ABBOTT_1000000
1000001 AGCO_1000001
1000002 ALFA LAVAL_1000002
1000003 ALSTOM POWER INDIA LIMITED_1000003
1000004 AMERICAN BUREAU OF SHIPPING_1000004

SQL FIDDLE

DEMO

You can use RIGHT together with CHARINDEX :

SQL Fiddle

UPDATE tbl
    SET Code = RIGHT(Name, LEN(Name) - CHARINDEX('_', Name))
WHERE CHARINDEX('_', Name) > 0
UPDATE <table>
SET name = STUFF(name, 1, CHARINDEX('_', name), '')
WHERE name like '%[_]%'

You can do this: First, you select the number that you want to place as code

select substr(name,-1,7) from table_name

After this, you can update the table.So,The complete statement will be :

update table_name t set t.code = (select substr(name,-1,7) from table_name where code = t.code);

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