假设我在MS SQL 2000中有以下表
Id | description | quantity |
-------------------------------
1 my desc 3
2 desc 2 2
我需要根据数量显示多行,所以我需要以下输出:
Id | description | quantity |
-----------------------------
1 my desc 1
1 my desc 1
1 my desc 1
2 desc 2 1
2 desc 2 1
任何想法如何实现这一目标?
答案 0 :(得分:3)
这很好用,不需要任何游标。也可以在没有数字表的情况下将某些东西搞砸。
注意如果采用这种解决方案,我会保留一个数字表,而不是每次运行查询时都不重新创建它。
create table #splitme (Id int, description varchar(255), quantity int)
insert #splitme values (1 ,'my desc', 3)
insert #splitme values (2 ,'desc 2', 2)
create table #numbers (num int identity primary key)
declare @i int
select @i = max(quantity) from #splitme
while @i > 0
begin
insert #numbers default values
set @i = @i - 1
end
select Id, description, 1 from #splitme
join #numbers on num <= quantity
答案 1 :(得分:0)
DECLARE @Id INT
DECLARE @Description VARCHAR(32)
DECLARE @Quantity INT
DECLARE @Results TABLE (Id INT, [description] VARCHAR(32), quantity INT)
DECLARE MyCursor CURSOR FOR
SELECT Id, [description], quantity
FROM
MyTable
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO @Id, @Description, @Quantity
WHILE @@FETCH_STATUS = 0
BEGIN
WHILE @Quantity > 0
BEGIN
INSERT INTO @Results (
Id,
[description],
quantity
) VALUES (
@Id,
@Description,
1
)
SET @Quantity = @Quantity - 1
END
FETCH NEXT FROM MyCursor INTO @Id, @Description, @Quantity
END
CLOSE MyCursor
DEALLOCATE MyCursor
SELECT *
FROM
@Results
顺便说一句,游标通常被认为是邪恶的。所以我会建议反对这样的事情,并提前感谢所有人的火焰;)(但它应该工作)