공통 스크립트 - 지정된 문자열을 여러 줄 데이터로 버스트

17209 단어 문자열
--==============================================
-- 
--==============================================
ALTER FUNCTION dbo.ufn_SplitString
(
  @SourceSql VARCHAR(MAX) ,
  @StrSeprate VARCHAR(10)
)
RETURNS @temp TABLE (C1 VARCHAR(MAX) )
AS
BEGIN
    DECLARE @i INT
    SET @SourceSql = RTRIM(LTRIM(@SourceSql))
    SET @i = CHARINDEX(@StrSeprate, @SourceSql)
    WHILE @i >= 1
        BEGIN
            INSERT  @temp
            VALUES  ( LEFT(@SourceSql, @i - 1) )
            SET @SourceSql = SUBSTRING(@SourceSql, @i + 1,
                                       LEN(@SourceSql) - @i)
            SET @i = CHARINDEX(@StrSeprate, @SourceSql)
        END
    IF @SourceSql <> '\'
        INSERT  @temp
        VALUES  ( @SourceSql )
    RETURN
END
GO
--=====================================================
--
SELECT * FROM dbo.ufn_SplitString('ABDC,BDF,DEF,,',',')
-- 
SELECT * FROM dbo.ufn_SplitString('ABDC,BDF,DEF,,',',')
WHERE C1<>''

버전 2
--===============================================================
-- 
CREATE FUNCTION [dbo].[SplitString]
(    
  @Input NVARCHAR(MAX), --input string to be separated    
  @Separator NVARCHAR(MAX)=',', --a string that delimit the substrings in the input string    
  @RemoveEmptyEntries BIT=1 --the return value does not include array elements that contain an empty string
)
RETURNS @TABLE TABLE 
(    
  [Id] INT IDENTITY(1,1),    
  [VALUE] NVARCHAR(MAX)) 
AS
BEGIN     
  DECLARE @Index INT, @Entry NVARCHAR(MAX)    
  SET @Index = CHARINDEX(@Separator,@Input)    

  WHILE (@Index>0)    
  BEGIN        
    SET @Entry=LTRIM(RTRIM(SUBSTRING(@Input, 1, @Index-1)))                

      IF (@RemoveEmptyEntries=0) OR (@RemoveEmptyEntries=1 AND @Entry<>'')            
        BEGIN                
          INSERT INTO @TABLE([VALUE]) VALUES(@Entry)            
        END        

        SET @Input = SUBSTRING(@Input, @Index+DATALENGTH(@Separator)/2, LEN(@Input))        
        SET @Index = CHARINDEX(@Separator, @Input)    
  END        

  SET @Entry=LTRIM(RTRIM(@Input))    
  IF (@RemoveEmptyEntries=0) OR (@RemoveEmptyEntries=1 AND @Entry<>'')        
    BEGIN            
      INSERT INTO @TABLE([VALUE]) VALUES(@Entry)        
    END    
RETURN

END 

--===============================================================
-- 
DECLARE @str1 VARCHAR(MAX), @str2 VARCHAR(MAX), @str3 VARCHAR(MAX)

SET @str1 = '1,2,3'
SET @str2 = '1###2###3'
SET @str3 = '1###2###3###'

SELECT [VALUE] FROM [dbo].[SplitString](@str1, ',', 1)
SELECT [VALUE] FROM [dbo].[SplitString](@str2, '###', 1)
SELECT [VALUE] FROM [dbo].[SplitString](@str3, '###', 0)

좋은 웹페이지 즐겨찾기