Select rows in sequential
- Table name is Items
Field : Item
And only 1 field and is indexed.
Select * from Items will give result as
Item
------
A
B
C
D
E
F
G
H
Need an output like ?i.e sequential
A B C
D E F
G H
and there is only 1 field and an index on it.
Can any one pls tell me how it is possible with sql query?- Moved byDan BenediktsonMSFTFriday, November 06, 2009 5:47 PM (From:SQL Server Data Access)
Answers
- try query below
declare @t table (item varchar(3))
insert into @t (item)
select 'A' union
select 'B' union
select 'C' union
select 'D' union
select 'E' union
select 'F' union
select 'G' union
select 'H' union
select 'I' union
select 'J' union
select 'K'
declare @item varchar(100)
set @item = (select e.item as [data()]
from @t e
for xml path (''))
Set @item = (select REPLACE(@item, ' ',''))
declare @len1 int
declare @len int
set @len =(select COUNT(*) from @t)/3
set @len1 = 0
declare @t2 table (item varchar(3))
while (@len > =0)
begin
insert into @t2 (item)
select SUBSTRING(@item, @len1*3+1 ,3)
set @len1 = @len1+1
set @len = @len -1
End
select * from @t2
Best Regards,
Melissa Suciadi
If you have found this post helpful, please click the 'Vote as Helpful ' link (the green triangle and number on the top-left).If this post answers your question, click the 'Mark As Answered ' link below. It helps others who experience the same issue in future to find the solution.
- Marked As Answer byZongqing LiMSFT, ModeratorTuesday, November 10, 2009 7:41 AM
All Replies
Could I know why you're looking for a solution for this problem? If you want to display the data on a web page like this, you could have a better choice.
<asp:DataList ID="dlItems" runat="server" RepeatDirection="Horizontal" RepeatLayout="Table" RepeatColumns="3" />
Thanks,
Hooray- try query below
declare @t table (item varchar(3))
insert into @t (item)
select 'A' union
select 'B' union
select 'C' union
select 'D' union
select 'E' union
select 'F' union
select 'G' union
select 'H' union
select 'I' union
select 'J' union
select 'K'
declare @item varchar(100)
set @item = (select e.item as [data()]
from @t e
for xml path (''))
Set @item = (select REPLACE(@item, ' ',''))
declare @len1 int
declare @len int
set @len =(select COUNT(*) from @t)/3
set @len1 = 0
declare @t2 table (item varchar(3))
while (@len > =0)
begin
insert into @t2 (item)
select SUBSTRING(@item, @len1*3+1 ,3)
set @len1 = @len1+1
set @len = @len -1
End
select * from @t2
Best Regards,
Melissa Suciadi
If you have found this post helpful, please click the 'Vote as Helpful ' link (the green triangle and number on the top-left).If this post answers your question, click the 'Mark As Answered ' link below. It helps others who experience the same issue in future to find the solution.
- Marked As Answer byZongqing LiMSFT, ModeratorTuesday, November 10, 2009 7:41 AM


