简体   繁体   中英

SQL Server select part of string

I have table like this

Column1
-------------------------------------------------------
nn=APPLE IPod 44454,o=0006,o=TOP8,nn=USA,nn=TOP8+
nn=SAMSUNG G5 487894,o=04786,o=T418,nn=JPN,nn=TO478+

And I need update that table and get result like this

Column1                                                 Column2
---------------------------------------------------------------
nn=APPLE IPod 44454,o=0006,o=TOP8,nn=USA,nn=TOP8+        44454
nn=SAMSUNG G5 487894,o=04786,o=T418,nn=JPN,nn=TO478+    487894

My idea is but I can not fit with first character:

update tablename 
set [column2] = SUBSTRING(column1, 1, CHARINDEX(' ', column1) - 1 (column1, CHARINDEX(' ', column1) + 1, LEN(column1))

Okay, given the second sample record, it looks like what you need is the last element of the space-delimited string in the first position of the comma-delimited string. So write yourself (or find) a string-splitter function that accepts a string and a delimiter, and then your parsing logic is:

  1. split the field at the commas
  2. take the first element
  3. split that element at the spaces
  4. take the last element

Does that make sense?

The following answer is based only on the two records you actually showed us. If we were to derive a rule from this, it might be that we want to extract the previous word (a product number) occurring immediately before the first comma in the string. If so, then we can try the following logic:

  • isolate the substring before the comma (eg nn=APPLE Ipod 44454 )
  • reverse that string ( 45444 dopI ELPPA=nn )
  • then take the substring of that before the first space ( 45444 )
  • finally reverse this substring to yield the product number we want ( 44454 )

Consider the following query, with data imported via a CTE:

WITH yourTable AS (
    SELECT 'nn=APPLE IPod 44454,o=0006,o=TOP8,nn=USA,nn=TOP8+' AS column1 UNION ALL
    SELECT 'nn=SAMSUNG G5 487894,o=04786,o=T418,nn=JPN,nn=TO478+'
),
update_cte AS (
    SELECT
        column1,
        column2,
        REVERSE(
            SUBSTRING(REVERSE(SUBSTRING(column1, 1, CHARINDEX(',', column1)-1)),
            1,
            CHARINDEX(' ', REVERSE(SUBSTRING(column1, 1, CHARINDEX(',', column1)-1))) - 1)
        ) AS col2
    FROM yourTable
)

SELECT column1, col2 FROM update_cte;

Output:

在此处输入图片说明

Demo here:

Rextester

If you wanted to update your table to bring in these column2 product IDs, then you can use the above CTE fairly easily:

UPDATE update_cte
SET column2 = col2;

This query can help you.

  UPDATE tablename SET [column2] =
    SUBSTRING((LEFT(column1,CHARINDEX(',',column1)-1)), CHARINDEX(' ', column1, CHARINDEX(' ',column1) +1 ) +1 ,LEN(column1))

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