How to split a string after specific character in SQL Server and update this value to specific column

前端 未结 8 1145
死守一世寂寞
死守一世寂寞 2020-12-01 09:59

I have table with data 1/1 to 1/20 in one column. I want the value 1 to 20 i.e value after \'/\'(front slash) is updated into other column in same

相关标签:
8条回答
  • 2020-12-01 10:39

    Use CHARINDEX. Perhaps make user function. If you use this split often.
    I would create this function:

    CREATE FUNCTION [dbo].[Split]
    (
        @String VARCHAR(max),
        @Delimiter varCHAR(1)
    )
    RETURNS TABLE 
    AS
    RETURN 
    (
        WITH Split(stpos,endpos) 
        AS(
            SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
            UNION ALL
            SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
                FROM Split
                WHERE endpos > 0
        )
        SELECT 'INT_COLUMN' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
            'STRING_COLUMN' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
        FROM Split
    )
    GO
    
    0 讨论(0)
  • 2020-12-01 10:43

    From: http://www.sql-server-helper.com/error-messages/msg-536.aspx

    To use function LEFT if not all data is in the form '1/12' you need this in the second line above:

    Set Col2 = LEFT(Col1, ISNULL(NULLIF(CHARINDEX('/', Col1) - 1, -1), LEN(Col1)))
    
    0 讨论(0)
  • 2020-12-01 10:46

    Try this:

    UPDATE YourTable
    SET Col2 = RIGHT(Col1,LEN(Col1)-CHARINDEX('/',Col1))
    
    0 讨论(0)
  • 2020-12-01 10:52

    I know this question is specific to sql server, but I'm using postgresql and came across this question, so for anybody else in a similar situation, there is the split_part(string text, delimiter text, field int) function.

    0 讨论(0)
  • 2020-12-01 10:53
    SELECT emp.LoginID, emp.JobTitle, emp.BirthDate, emp.ModifiedDate  , 
          CASE  WHEN emp.JobTitle  NOT LIKE '%Document Control%'  THEN emp.JobTitle
                ELSE SUBSTRING(emp.JobTitle,CHARINDEX('Document Control',emp.JobTitle),LEN('Document Control'))
          END 
          ,emp.gender,emp.MaritalStatus
    FROM   HumanResources.Employee [emp]
    WHERE  JobTitle LIKE '[C-F]%'
    
    0 讨论(0)
  • 2020-12-01 10:55

    Please find the below query also split the string with delimeter.

    Select Substring(@String1,0,CharIndex(@delimeter,@String1))
    
    0 讨论(0)
提交回复
热议问题