A stored procedure in which consecutive numbered serial numbers are spliced into a string.

Source: Internet
Author: User
Tags min query first row
Stored Procedure | serial number
User questions:
---------------------------------------
Test1 table
ID Start End
1 1 5
2 6 10
3 21 25
4 26 30
5 51 60
Hope to get results:
String:1-10,21-30,51-60
---------------------------------------

The solution of string concatenation using variable:

--Build Test table:
CREATE TABLE test1 (ID int,start int,[end] int)

--Add test data:
Insert Test1 Select 1,1,5
Union Select 2,6,10
Union Select 3,21,25
Union Select 4,26,30
Union Select 5,51,60

--a function to create a concatenation string:
CREATE PROCEDURE ProA
As
Begin

DECLARE @s varchar (8000)

--Give the variable a corresponding value in the first row of the table, cast (min (start)-1 is to be properly connected to the first line in the subsequent full table query. Note that if the serial number is starting at 0, '-' to be replaced with the other word Furu "+", the last select @s, then change back to the '-' number, the specific statement is: Select replace (@s, ' + ', '-'):
Select @s= + cast (min (start) as varchar (10)) + '-'
+ CAST (min (start)-1 as varchar (10))
From Test1

--Sequential query and concatenation of strings:
Select @s= Left (@s,len (@s)-charindex ('-', reverse (@s)) +1)
+ Case when cast (right (@s,charindex ('-', reverse (@s))-1) as int) +1
=start
Then cast ([end] as varchar (20))
else Right (@s,charindex ('-', reverse (@s))-1) + ', '
+ CAST (start as varchar (10)) + '-'
+ CAST ([end] as varchar (10))
End
From Test1
ORDER BY Start

--Returns the result:
Select @s

End

--Delete test table:
drop table Test1



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.