sql
  • sql-server-2008
  • 2013-08-26 2 views 1 likes 
    1

    응용 프로그램을 변경해야하며 필요한 첫 번째 작업은 데이터베이스 테이블의 필드를 변경하는 것입니다. 이 표에 I 지금은SQL을 별도의 문자로 나누기

    [수정 '[A] [B] [C], [D] [E] [F]로 변경해야 "ABCDEF"예 1 내지 6의 단일 문자를 가지고 ] 그것은 같은 분야에 머물기위한 것입니다. 그래서 field = 'abcdef'와 after field = '[a] [b] [c] [d] [e] [f]'앞에.

    이 작업을 수행하는 좋은 방법은 무엇입니까?

    rg. 에릭

    답변

    2

    당신은 다음과 같은 기능을 사용하여 문자를 구분하는 문자열을 분할 할 수 있습니다 :

    create function ftStringCharacters 
    (
        @str varchar(100) 
    ) 
    returns table as 
    return 
        with v1(N) as (
         select 1 union all select 1 union all select 1 union all select 1 union all select 1 
         union all 
         select 1 union all select 1 union all select 1 union all select 1 union all select 1 
        ), 
        v2(N) as (select 1 from v1 a, v1 b), 
        v3(N) as (select top (isnull(datalength(@str), 0)) row_number() over (order by @@spid) from v2) 
        select N, substring(@str, N, 1) as C 
        from v3 
    GO 
    

    그리고로 적용하는 기능을 사용하지 않고

    update t 
    set t.FieldName = p.FieldModified 
    from TableName t 
        cross apply (
         select (select quotename(s.C) 
         from ftStringCharacters(t.FieldName) s 
         order by s.N 
         for xml path(''), type).value('text()[1]', 'varchar(20)') 
        ) p(FieldModified) 
    

    SQLFiddle sample

    +0

    완벽하게 작동했습니다! 고맙습니다!! – Eric

    2
    DECLARE @text NVARCHAR(50) 
    
    SET @text = 'abcdef' 
    
    DECLARE @texttable TABLE (value NVARCHAR(1)) 
    
    WHILE (len(@text) > 0) 
    BEGIN 
        INSERT INTO @texttable 
        SELECT substring(@text, 1, 1) 
    
        SET @text = stuff(@text, 1, 1, '') 
    END 
    
    select * from @texttable 
    
    +0

    감사하지만 같은 분야에 머물러 있어야한다는 것을 의미했습니다. 더 명확하게 반영하도록 내 질문을 변경했습니다. – Eric

    0

    를 :

    declare @t table(C varchar(18)) 
    insert @t values('abc'), ('1234'), (' 1234a') 
    
    ;with CTE as 
    (
    select C, '[' + substring(c, a.n, 1) + ']' v, rn from 
    (select 1 n union all 
    select 2 union all 
    select 3 union all 
    select 4 union all 
    select 5 union all 
    select 6) a 
    cross apply 
    (select c, row_number() over (order by C) rn from @t group by c) b 
    where a.n <= len(C) 
    ) 
    update t3 
    set C = t4.[value] 
    FROM @t t3 
    JOIN 
    (
    select C, 
        ( 
         select v 
         from CTE t1 
         where t1.rn = t2.rn 
         for xml path(''), type 
        ).value('.', 'varchar(18)') [value] 
    from CTE t2 
    group by t2.rn, C 
    ) t4 
    ON t3.C = t4.C 
    
    SELECT * FROM @t 
    
    관련 문제