日期:2014-05-17 浏览次数:20594 次
ALTER PROC UP_test
@string VARCHAR(MAX)
AS
begin
DECLARE @counter INT, @sql NVARCHAR(MAX), @MaxCount INT, @FieldList NVARCHAR(MAX)
SET @counter = 1
CREATE TABLE #temp(id INT, ch CHAR(1))
WHILE(@counter <= LEN(@string))
BEGIN
INSERT #temp VALUES(@counter, substring(@string, @counter, 1))
SET @counter = @counter + 1
END
SELECT @MaxCount = MAX(cnt) FROM
(SELECT ch, cnt=COUNT(*) FROM #temp GROUP BY ch) T
SET @FieldList = STUFF(
(
SELECT ','+QUOTENAME(number+1) FROM master..spt_values
WHERE type='p' AND number < @MaxCount
FOR XML PATH('')
),1,1,''
)
SET @sql = N'
select * from
(select rowid=row_number() over(partition by ch order by id),* from #temp) a
pivot
(max(id) for rowid in('+ @FieldList +')) b
'
EXEC(@sql)
end
GO
EXEC up_test 'ABCDEE'
/*
ch 1 2
A 1 NULL
B 2 NULL
C 3 NULL
D 4 NULL
E 5 6
*/