Rotate a column

0

Please login or register to vote for this query.

(click on this box to dismiss)

Stack Overflow

Q&A for professional and enthusiast programmers

DECLARE @ table(x varchar(max),i int identity)
DECLARE @c INT=20

INSERT @ values
('A line with more than k characters.'),
('A longer line with more than k character.'),
('A short line.'),
('Rotate here: ------v--'),
('This is long enough.'),
('This is not enough.'),
('Wrapping around to the first line.')

;WITH C as
(
SELECT rank() over(order by i)r,count(*)over()c,*
FROM @
WHERE len(x)>=@c
), D as
(
SELECT stuff(c.x,@c,1,substring(d.x,@c,1))m,c.i
FROM c,c d WHERE d.r%c.c+1=c.r
)
SELECT isnull(m,x) FROM @ z LEFT JOIN d ON z.i=d.i

Enter Parameters

Options:
Switch to meta site
loading Hold tight while we fetch your results