In SQLServer2005 + you can use the option with a common table expression
DECLARE @tblKeywords TABLE (Keyword1 VARCHAR(MAX), Keyword2 VARCHAR(MAX), Keyword3 VARCHAR(MAX)) ;WITH cte AS ( SELECT Keyword, ROW_NUMBER() OVER (ORDER BY KeywordID) AS RowNum FROM dbo.t_SMSKeyword ) INSERT @tblKeywords(Keyword1, Keyword2, Keyword3) SELECT c1.Keyword, c2.Keyword, c3.Keyword FROM cte c1 JOIN cte c2 ON c1.RowNum + 3 = c2.RowNum JOIN cte c3 ON c2.RowNum + 3 = c3.RowNum WHERE c1.RowNum BETWEEN 1 and 3
See SQLFiddle Example
Select 4 rows in the first column and 3 rows for the other columns
DECLARE @tblKeywords TABLE (Keyword1 VARCHAR(MAX), Keyword2 VARCHAR(MAX), Keyword3 VARCHAR(MAX)) ;WITH cte AS ( SELECT Keyword, ROW_NUMBER() OVER (ORDER BY KeywordID) AS RowNum FROM dbo.t_SMSKeyword ) INSERT @tblKeywords(Keyword1, Keyword2, Keyword3) SELECT c1.Keyword, c2.Keyword, c3.Keyword FROM cte c1 LEFT JOIN cte c2 ON c1.RowNum + 4 = c2.RowNum AND c2.RowNum < 8 LEFT JOIN cte c3 ON c2.RowNum + 3 = c3.RowNum WHERE c1.RowNum BETWEEN 1 and 4 SELECT * FROM @tblKeywords
Example for second SQLFiddle solution
source share