Tuesday, July 31, 2018

SQL Function for returning comma separate values

SQL Function for returning comma separate values

USE [DBName]
GO
/****** Object:  UserDefinedFunction [dbo].[BreakStringIntoTableRows]    Script Date: 07/31/2018 04:23:12 ******/
SET ANSI_NULLS ON


GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[BreakStringIntoTableRows] (@CommadelimitedString   varchar(1000))
RETURNS   @Result TABLE (Column1   VARCHAR(100))
AS
BEGIN
        DECLARE @IntLocation INT
        WHILE (CHARINDEX(',',    @CommadelimitedString, 0) > 0)
        BEGIN
              SET @IntLocation =   CHARINDEX(',',    @CommadelimitedString, 0)     
              INSERT INTO   @Result (Column1)
              --LTRIM and RTRIM to ensure blank spaces are   removed
              SELECT RTRIM(LTRIM(SUBSTRING(@CommadelimitedString,   0, @IntLocation))) 
              SET @CommadelimitedString = STUFF(@CommadelimitedString,   1, @IntLocation,   '')
        END
        INSERT INTO   @Result (Column1)
        SELECT RTRIM(LTRIM(@CommadelimitedString))--LTRIM and RTRIM to ensure blank spaces are removed
        RETURN
END

No comments:

Post a Comment