如何在递归存储过程中使用pivot

时间:2012-12-31 11:51:52

标签: sql-server stored-procedures pivot

我根据varchar分隔spaces(我知道空格的数量)

我使用stored procedure (Recursive)来执行此操作

Alter procedure [dbo].[1234]
   @name varchar(100),
   @count int 
AS 
BEGIN 

    if @count=1
    begin
        set @name=SUBSTRING(@name,CHARINDEX(' ',@name,1)+1,LEN(@name))
        select @name
    end
    if @count>1
    begin
        select SUBSTRING(@name,1,CHARINDEX(' ',@name,1)-1)
        set @count=@count-1
        set @name=SUBSTRING(@name,CHARINDEX(' ',@name,1)+1,LEN(@name))
        exec [dbo].[1234] @name,@count
    end
END

我在

上执行以下SP
exec [dbo].[1234] 'a b c d e f g h',8

我的结果是 enter image description here

但我希望我的结果为

Image http://s9.postimage.org/meqqr3dqn/result1.png

1 个答案:

答案 0 :(得分:3)

Alter procedure [dbo].[1234]
   @name varchar(100)
as   
Select @name='Select' + ''''+Replace(@name,' ',''',''')+''''
EXEC( @name)

GO

[1234] 'A b c d e f'

这是SQL Fiddle demo