SQL implementation of the Split function script _mssql

Source: Internet
Author: User

Copy Code code as follows:

--Create a function with two parameters in the function
Create FUNCTION [dbo]. [Splittotable]
(
@SplitString nvarchar (max),--the string entered
@Separator nvarchar (10) = ' '--segmentation condition
)
--The returned data is a table
RETURNS @SplitStringsTable TABLE
(
[id] int identity (1,1),
[value] nvarchar (max)
)
As
BEGIN
DECLARE @CurrentIndex int;--Current Index
DECLARE @NextIndex int;--Next Index
DECLARE @ReturnText nvarchar (max);--Return content
SELECT @CurrentIndex =1;--Set the current index to an initial value of 1
--Executes the loop body when the current index is less than the string length
while (@CurrentIndex <=len (@SplitString))
BEGIN
The--charindex function returns the starting position of a character or string in another string. The CHARINDEX function calls the following methods:
--charindex (expression1, expression2 [, Start_location])
-Expression1 is the character to look for in the expression2, start_location is the CHARINDEX function begins to find expression2 in the expression1 position.
SELECT @NextIndex =charindex (@Separator, @SplitString, @CurrentIndex);
IF (@NextIndex =0 OR @NextIndex is NULL)
SELECT @NextIndex =len (@SplitString) +1;
--Functional usage: SUBSTRING (expression, start, length)
SELECT @ReturnText =substring (@SplitString, @CurrentIndex, @NextIndex-@CurrentIndex);
INSERT into @SplitStringsTable ([value]) VALUES (@ReturnText);
SELECT @CurrentIndex = @NextIndex +1;
End
return;
End
Go
--Test function
SELECT * FROM dbo. Splittotable (' a,b,c,d,e,f,g ', ', ', ')

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.