------------------------MSSQL中排列组合的实现------------------------------------

--排列组合

--执行方法:exec [Arrange] '1,2,3'

--input:1,2,3

--output:--1 --2 --3 --1,2 --1,3 --2,3 --1,2,3

Create PROCEDURE [dbo].[Arrange]

     @input varchar(100)

AS

BEGIN

    SET NOCOUNT ON

   

    if(len(@input)<1) return

    DECLARE @tableArrange Table

    (

        id int identity(1,1),

        arrangeValue varchar(100),

        maxid int,

        lenOfValue int

    )

    declare @split varchar(10)

    set @split = ','

    declare @startIndex int

    set @startIndex = 1

    declare @endIndex int

    set @endIndex = charindex(@split,@input,@startIndex)

    declare @items varchar(100)

    while(@endIndex<>0)

    begin

        set @items = Substring(@input,@startIndex,@endIndex-@startIndex)

        if len(@items)>0
       
        insert into @tableArrange(arrangeValue) values(@items)

        set @startIndex = @endIndex + 1

        set @endIndex = charindex(@split,@input,@startIndex)           

    end

    set @items = Substring(@input,@startIndex,len(@input)-@startIndex+1 )

    if len(@items)>0 insert into @tableArrange(arrangeValue) values(@items)

   

    update @tableArrange set maxid=id,lenOfValue=1

   

    declare @count int--

    declare @currentlen int   

    declare @value varchar(100)

    declare @valueInsert varchar(100)

    declare @start int

    declare @end int

    declare @i int

    declare @j int

    declare @maxid int

    declare @lenofvalue int

    select @count = max(id) from @tableArrange

    set @currentlen=1

    while(@currentlen<@count)

    begin

        select @start=min(id),@end=max(id) from @tableArrange where lenOfValue=@currentlen

        set @i=@start       

        while(@i<@end)

        begin

            select @maxid=maxid,@value=arrangeValue,@lenofvalue=lenofvalue from @tableArrange where id=@i

            set @j=@maxid+1

            while(@j<=@count)

            begin

                select @valueInsert=@value+','+arrangeValue from @tableArrange where id=@j

                insert into @tableArrange(arrangeValue,maxid,lenofvalue)

                    values(@valueInsert,@j,@lenofvalue+1)

                set @j=@j+1

            end

            set @i=@i+1

        end

        set @currentlen=@currentlen+1

    end

    select arrangeValue from @tableArrange

   
SET NOCOUNT ON

END

go

exec [Arrange]  '1,2,3,4'

go

drop proc [Arrange]

go

/*

arrangeValue
----------------------------------------------------------------------------------------------------
1
2
3
4
1,2
1,3
1,4
2,3
2,4
3,4
1,2,3
1,2,4
1,3,4
2,3,4
1,2,3,4

*/

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值