Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将Sql Int值拆分为多行_Sql - Fatal编程技术网

如何将Sql Int值拆分为多行

如何将Sql Int值拆分为多行,sql,Sql,假设我在MS SQL 2000中有下表 Id | description | quantity | ------------------------------- 1 my desc 3 2 desc 2 2 我需要根据数量显示多行,因此我需要以下输出: Id | description | quantity | ----------------------------- 1 my desc 1 1 my desc

假设我在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
有没有办法做到这一点

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

顺便说一句,游标通常被认为是邪恶的。所以我会建议大家不要这样做,并提前感谢大家的热情;但是它应该可以工作

这很好,不需要任何游标。也有可能在没有数字表的情况下将某些东西拼凑出来

注意:如果使用这种解决方案,我将保留一个数字表,而不是每次运行查询时都重新创建它

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

诚然,如果将@i设置为splitme的最大数量,它将是完美的。无论如何+1!我的意思是在while循环中,这样你就不会循环10000次,如果其中一个数量是10001。选择max将消除这种情况。