USE <Database_Name>
GO
IF OBJECT_ID(N'udf__ListToPairColumns') IS NOT NULL
DROP FUNCTION udf__ListToPairColumns
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- *****************************************************************************
-- Name : udf__ListToPairColumns
-- Author : Chandra Gunawan
-- Date : 02-Jun-2009
-- Description : Convert a delimited list of item into 2 columns
-- Parameters :
-- @pList vchr(8000) Delimited list of item to split
-- format: []
-- example: A=1,B=2,C=3
-- @pDelimiter1 vchr(1) Primary delimiter (bigger group) (dlm1)
-- @pDelimiter2 vchr(1) Secoundary delimiter (smaller group) (dlm2)
--
-- Usage Sample :
-- -------------------------------------------------
-- SELECT * FROM dbo.udf__ListToPairColumns('a=1,b=2,c=3', ',', '=')
-- -------------------------------------------------
--
-- Maintenance Log
-- =============================================================================
-- Date ID Description
-- -----------------------------------------------------------------------------
-- 02-Jun-09 chg Initial Version
-- *****************************************************************************
CREATE FUNCTION dbo.udf__ListToPairColumns
(
@pList varchar(8000),
@pDelimiter1 varchar(1) = ',',
@pDelimiter2 varchar(1) = '='
)
RETURNS @pTable TABLE
(
item_nm varchar(100),
item_val varchar(1000)
)
BEGIN
DECLARE @iSpot smallint,
@cPar varchar(8000),
@cVal varchar(8000),
@cSql varchar(8000)
IF ISNULL(@pDelimiter1, '') = '' SET @pDelimiter1 = ','
IF ISNULL(@pDelimiter2, '') = '' SET @pDelimiter2 = '='
WHILE @pList <> ''
BEGIN
SET @iSpot = CHARINDEX(@pDelimiter1, @pList)
IF @iSpot > 0
BEGIN
SET @cPar = LEFT(@pList, @iSpot-1)
SET @pList = RIGHT(@pList, LEN(@pList) - @iSpot)
END
ELSE BEGIN
SET @cPar = @pList
SET @pList = ''
END
SET @iSpot = CHARINDEX(@pDelimiter2, @cPar)
IF @iSpot > 0
SELECT @cVal = RIGHT(@cPar, LEN(@cPar) - @iSpot),
@cPar = LEFT(@cPar, @iSpot - 1)
ELSE
SET @cVal = ''
INSERT @pTable SELECT @cPar, @cVal
END
RETURN
END
GO
GRANT SELECT ON udf__ListToPairColumns TO public
GO
No comments:
Post a Comment