복붙노트

[SQL] 행으로 분할 열 데이터에 대한 SQL 쿼리

SQL

행으로 분할 열 데이터에 대한 SQL 쿼리

나는 아니오 그리고 선언 등이 개 필드를 겪고 점에서 SQL 테이블을 데

Code  Declaration
123   a1-2 nos, a2- 230 nos, a3 - 5nos

그 코드로의 선언을 표시해야합니다 :

Code  Declaration 
123   a1 - 2nos 
123   a2 - 230nos 
123   a3 - 5nos

그 코드 행에 열 데이터를 분할해야합니다.

해결법

  1. ==============================

    1.데이터 분리 이러한 유형의, 나는 분할 함수를 만드는 제안 :

    데이터 분리 이러한 유형의, 나는 분할 함수를 만드는 제안 :

    create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1))       
    returns @temptable TABLE (items varchar(MAX))       
    as       
    begin      
        declare @idx int       
        declare @slice varchar(8000)       
    
        select @idx = 1       
            if len(@String)<1 or @String is null  return       
    
        while @idx!= 0       
        begin       
            set @idx = charindex(@Delimiter,@String)       
            if @idx!=0       
                set @slice = left(@String,@idx - 1)       
            else       
                set @slice = @String       
    
            if(len(@slice)>0)  
                insert into @temptable(Items) values(@slice)       
    
            set @String = right(@String,len(@String) - @idx)       
            if len(@String) = 0 break       
        end   
    return 
    end;
    

    그런 다음 쿼리에서 이것을 사용하면 기존 테이블에 가입 외부를 적용 할 수 있습니다 :

    select t1.code, s.items declaration
    from yourtable t1
    outer apply dbo.split(t1.declaration, ',') s
    

    결과를 생성 할 것이다 :

    | CODE |  DECLARATION |
    -----------------------
    |  123 |     a1-2 nos |
    |  123 |  a2- 230 nos |
    |  123 |    a3 - 5nos |
    

    데모와 SQL 바이올린을 참조하십시오

    또는이 유사한 CTE 버전을 구현할 수 있습니다 :

    ;with cte (code, DeclarationItem, Declaration) as
    (
      select Code,
        cast(left(Declaration, charindex(',',Declaration+',')-1) as varchar(50)) DeclarationItem,
             stuff(Declaration, 1, charindex(',',Declaration+','), '') Declaration
      from yourtable
      union all
      select code,
        cast(left(Declaration, charindex(',',Declaration+',')-1) as varchar(50)) DeclarationItem,
        stuff(Declaration, 1, charindex(',',Declaration+','), '') Declaration
      from cte
      where Declaration > ''
    ) 
    select code, DeclarationItem
    from cte
    
  2. ==============================

    2.

    Declare @t Table([Code] int, [Declaration] varchar(32));    
    Insert Into @t([Code], [Declaration])
    Values(123, 'a1-2 nos, a2- 230 nos, a3 - 5nos')
    
    Select 
        x.[Code]
        ,t.Declaration  
        From
        (
            Select 
            *,
            Cast('<X>'+Replace(t.[Declaration],',','</X><X>')+'</X>' As XML) As record
    
            From @t t
        )x
        Cross Apply
        ( 
            Select fdata.D.value('.','varchar(50)') As Declaration 
            From x.record.nodes('X') As fdata(D)
        ) t
    

    몇 번 설정 기반 접근 방식을 사용하여 I는이 SQL Server의 동일한 분할 기능에 대해 블로그에 한 백업

    또한, 지난 15 년 이후 동일한에 대한 답을 유지하고있다 ERLAND Sommarskogblog를 방문하십시오.

  3. ==============================

    3.이 시도....

    이 시도....

    declare @col1 varchar(100),@CurentSubString varchar(100)
    
    create table #temp
    (
        col1 varchar(50)
    )
    
    DECLARE CUR   CURSOR
    FOR     SELECT  col1
            FROM    your_table
    open    CUR
    
    FETCH   next 
    FROM    CUR
    INTO    @col1
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
    
        WHILE   CHARINDEX (@col1, ';') <> 0
        BEGIN
        SET @CurentSubString    =   SUBSTRING(@col1,1,CHARINDEX (@col1, ';'))
        SET @col1 = SUBSTRING(@col1,CHARINDEX (@col1, ';')+1,len(@col1))
    
        insert into #temp
        select @CurentSubString
    END
    
    
    IF CHARINDEX (@col1, ';') = 0 and isnull(@col1,'')!= '' 
    BEGIN
        INSERT INTO #temp
        SELECT @col1
    END
    
    
    FETCH   next 
    FROM    CUR
    INTO    @col1
    
    END
    
    
    select  * 
    From    #temp
    
    CLOSE   CUR
    DEALLOCATE CUR
    
  4. from https://stackoverflow.com/questions/13527537/sql-query-to-split-column-data-into-rows by cc-by-sa and MIT license