-- == Sample Code == --SELECT * FROM fn_SplitZ --('?UID=N0464A&Section=Auditor General&Firm=GenDiesel&AI=Second',',') -- Returns: -- Col1 | Col2 -- UID | N0464A -- Section | Auditor General -- Firm | GenDiesel -- AI | Second -- == END Sample Code == -- Fn_SplitZ() Function -- Joe Johnston 03:30 10/17/2002 -- This code loosly emulates the VB Split command CREATE FUNCTION fn_SplitZ(@sText varchar(8000),@sDelim varchar(20) = ',') RETURNS @retArray TABLE (Col1 varchar(8000), Col2 varchar(8000)) AS BEGIN DECLARE @Col1 varchar(8000), @Col2 varchar(8000), @bcontinue bit, @iStrike smallint, @iDelimlength tinyint IF @sDelim = 'Space' BEGIN SET @sDelim = ' ' END -- Clean up our input string with a little code from Carl SET @sText = LTrim(REPLACE(REPLACE(REPLACE(@sText, '?',''), '=',',') , '&',','))+@sDelim -- Set initial length SET @iDelimlength = DATALENGTH(@sDelim) -- Out loop control var SET @bcontinue = 1 IF NOT ((@iDelimlength = 0) or (@sDelim = 'Empty')) BEGIN WHILE @bcontinue = 1 BEGIN --If you can find the delimiter in the text, retrieve the first element and write it IF CHARINDEX(@sDelim, @sText)>0 BEGIN SET @Col1 = SUBSTRING(@sText,1, CHARINDEX(@sDelim,@sText)-1) BEGIN INSERT @retArray (Col1) VALUES ( @Col1) END --Trim the element and its delimiter from the front of the string. Increment the index and loop. SET @iStrike = DATALENGTH(@Col1) + @iDelimlength SET @sText = LTrim(Right(@sText,DATALENGTH(@sText) - @iStrike)) END --If you can find the delimiter in the text, retrieve the Second element and write it IF CHARINDEX(@sDelim, @sText)>0 BEGIN SET @Col2 = SUBSTRING(@sText,1, CHARINDEX(@sDelim,@sText)-1) BEGIN UPDATE @retArray SET Col2 = @Col2 WHERE Col1 = @Col1 END --Trim the element and its delimiter from the front of the string. Increment the index and loop. SET @iStrike = DATALENGTH(@Col2) + @iDelimlength SET @sText = LTrim(Right(@sText,DATALENGTH(@sText) - @iStrike)) END ELSE BEGIN --If you can’t find the delimiter in the text, @sText is the last value in @retArray. -- We have left this in case of a Param='' case. SET @Col1 = @sText BEGIN INSERT @retArray (Col1) VALUES (@Col1) END --Exit the WHILE loop. SET @bcontinue = 0 END END END DELETE FROM @retArray where rtrim(col1) = '' -- Clean up any left overs RETURN END
"If ye love wealth better than liberty, the tranquility of servitude better than the animated contest of freedom, go home from us in peace. We ask not your counsel or arms. Crouch down and lick the hands which feed you. May your chains set lightly upon you, and may posterity forget that ye were our countrymen."
~Samuel Adams