Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
kond.mohan
Posting Yak Master
213 Posts |
Posted - 2012-03-09 : 04:48:05
|
HI,I HAVE USED SQL QUERYONE OF MY FIELD EXISTED LIKE ABC|(PIPE SYMBOL)CDE|EFGSDF|SDF|DFS|SFD|SFD|ERW|QWE|tTY| WE NEED TO SPLIT THE FIRST COLUMN ROW LIKE THIS WAYabc,cde,efghow can i get data this way can anybody know the logic help me |
|
webfred
Master Smack Fu Yak Hacker
8781 Posts |
Posted - 2012-03-09 : 05:40:32
|
[code]-- First we need a function to split the valuesif object_id('fnParseArray') is not nullbegin drop function fnParseArrayendgoCREATE FUNCTION dbo.fnParseArray (@array VARCHAR(max),@separator CHAR(1))RETURNS @T Table (occ int,col1 varchar(50))AS BEGINDECLARE @separator_position INT DECLARE @array_value VARCHAR(max)declare @occurence int =1 if (left(@array,1)=@separator)begin set @array=stuff(@array,1,1,'')endif (right(@array,1)<>@separator)begin SET @array = @array + @separatorend-- Loop through the string searching for separtor charactersWHILE PATINDEX('%' + @separator + '%', @array) <> 0 BEGIN SELECT @separator_position = PATINDEX('%' + @separator + '%',@array) SELECT @array_value = LEFT(@array, @separator_position - 1) INSERT into @T VALUES (@occurence,@array_value) set @occurence = @occurence + 1 SELECT @array = STUFF(@array, 1, @separator_position, '')ENDRETURN ENDgo-- Now we need your sample data in a table variable to have a testdeclare @yak table(id int identity(1,1), testCol varchar(255))insert @yakselect 'ABC|CDE|EFG' union allselect 'SDF|SDF|DFS|SFD|SFD|ERW|' union allselect 'QWE|tTY|'-- show sample dataselect * from @yak-- the solutionselect y.id,t2.col1from @yak y outer apply dbo.fnParseArray(testCol,'|') t2[/code] No, you're never too old to Yak'n'Roll if you're too young to die. |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-03-09 : 11:52:55
|
http://visakhm.blogspot.com/2010/02/parsing-delimited-string.html------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|