How to use pivot in a recursive stored procedure

2019-08-22 16:13发布

I am separating a varchar according to spaces (I know the no. of spaces)

I am using a stored procedure (Recursive) to do so

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

I execute the following SP on

exec [dbo].[1234] 'a b c d e f g h',8

And my result is enter image description here

but i want my result as

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

1条回答
你好瞎i
2楼-- · 2019-08-22 16:34
Alter procedure [dbo].[1234]
   @name varchar(100)
as   
Select @name='Select' + ''''+Replace(@name,' ',''',''')+''''
EXEC( @name)

GO

[1234] 'A b c d e f'

Here's a SQL Fiddle demo.

查看更多
登录 后发表回答