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 @t table(x varchar(max),i int identity)
DECLARE @ INT=20

INSERT @t 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,sum(1)over()c,*
  FROM @t
  WHERE len(x)>=@
)
SELECT isnull(stuff(c.x,@,1,substring(e.x,@,1)),t.x)
FROM @t t
LEFT JOIN
c ON t.i=c.i
LEFT JOIN c e ON e.r%c.c+1=c.r

Enter Parameters

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