Friday, September 9, 2011

How to split values in sql server?

 Here i am showing how to split values in Sql server as Split function did  in c#

Why should we take some string value from a table and split that on our C# programming why not in the SQL programming? so many times we prefer to save a One to Many relation type with a single field in a SQL db table by concatenating the selected item with a separator like"1,4,8,7". But as we know SQL don't have a function like C# has Split(). So many programmer takes that value from db and split it in the C# code. But i am not happy with that as always going for better option and i implement this Function for that and thanks god its works..

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create function [dbo].[fnSplit](
    @sInputList VARCHAR(8000) -- List of delimited items
  , @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
) RETURNS @List TABLE (item VARCHAR(8000))

BEGIN
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
 BEGIN
 SELECT
  @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
  @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))

 IF LEN(@sItem) > 0
  INSERT INTO @List SELECT @sItem
 END

IF LEN(@sInputList) > 0
 INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END
--select * from dbo.fnSplit('1,2,34,5', ',') where item=34
--select * from dbo.fnSplit('1,2,34,5', ',')

Hope this will helps you tooooo :)

No comments:

Post a Comment