MS SQL server2k string splitting and merging processing code

Source: Internet
Author: User
server| string-- MS SQL server2k string splitting and merging processing code

--string split processing code
CREATE FUNCTION F_splitstr (
@s varchar (8000),--string to be split
@split varchar (10)--Data separator
) RETURNS TABLE
As
--select Top 8000 id=identity (int,1,1) into DBO.TB_SPLITSTR--the auxiliary table to be used by the string splitting function.
--from syscolumns A,syscolumns b

Return (
SELECT Col=cast (SUBSTRING (@s,id,charindex (@split, @s+ @split, ID)-id) as varchar (100))
From Tb_splitstr
WHERE Id<=len (@s+ ' a ')
and CHARINDEX (@split, @split +@s,id) =id)
--drop Table Tb_splitstr
Go

/*-Use the above function to split the string field character of a table to handle the code
DECLARE @id int,@c varchar (50)
Declare k cursor FOR SELECT * FROM Id_f--string to split original table (ID int,c varchar (50))
Open K
Fetch NEXT from K into @id, @c
while (@ @fetch_status =0)
Begin
INSERT into ID_YF-split result table (ID int,c varchar (50))
Select @id as id,c.* from F_splitstr (@c, ', ') as C
Fetch NEXT from K into @id, @c
End
Close K
Deallocate k
*/
--------------------------------------------------------------------------
--String Merge processing code
DECLARE @s varchar (300)
Set @s= '
SELECT @s=@s+c+ ', '
from [dbo]. [Id_h]--strings to be merged table [ID int,c varchar (50)]
Where ID <> (select top 1 ID from Id_h ORDER BY id DESC) Order by ID

Select @s=@s+ c from id_h where id = (select top 1 ID from Id_h ORDER by id DESC)
Select @s



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.