Database/MS-SQL | Posted by 아키텍처 2012. 4. 24. 17:49

구분된 문자를 배열로 만들기

 
 

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

 
/*
  사용예제  

  Declare @aryString  varchar(8000)
  Declare @G   varchar(1000)
  Declare @Idx   int
  Set @aryString = '1,2,3,4,5,6,'

  Set @Idx = CharIndex(',', @aryString)
  While 0 < @Idx
   Begin
    Set @G      = dbo.MakeArray(@aryString,'S',',')
    Set @aryString = dbo.MakeArray(@aryString,'F',',')

    --업무 처리 로직
    Print @G
    Set @Idx = CharIndex(',', @aryString)

   End
*/
ALTER  Function [dbo].[MakeArray](@FullStr varchar(8000), @Flag char(1), @GuBun char(1)) -- 입력값 (구분자에 따라서 연결해준 문자열)
 Returns varchar(8000) -- 출력형태
As
 Begin
  Declare
  @Idx   tinyint,
  @SelectStr  varchar(8000),
  @ReturnValue varchar(8000)

  Select @Idx = CharIndex(@GuBun,@FullStr)
  IF @Idx > 0 
   Begin
    IF @Flag = 'F'
      Select @ReturnValue = Substring(@FullStr, @Idx+1, Len(@FullStr))
    Else IF @Flag = 'S'
      Select @ReturnValue = Substring(@FullStr, 1, @Idx-1)
    Else
      Select @ReturnValue = 'FlagError'
   End
  Else
    Select @ReturnValue = 'NotArray'

 Return(@ReturnValue)
 End

Posted by 김준홍 (http://www.Juuun.com)