根据另一个表中的字段从表中插入或删除行

时间:2017-08-01 20:03:40

标签: sql-server sql-server-2008 tsql

我有一个非常复杂的问题。任何人都可以给我任何指示以下方案,

我有两张桌子。 tblone,tbltwo。我想根据tblone中的Quantity值在tbltwo中插入或删除记录。例如,如果tbl.Quantity为4并且我在tbltwo中有2行,那么我需要添加两行。如果tbl.Quantity为1且tbltwo有3行,我想删除2行。我真的很困惑。任何帮助表示赞赏。我尝试使用光标但没有成功。

SELECT Quantity
FROM tblOrder
WHERE visitid = 123123

结果是4

SELECT count(Product)
FROM tblProducts
WHERE visitid = 123123

结果是2

所以我想从tblTwo为visitId = 123123

添加两行

tblShipment

VisitID|Quantity|Type
12313      4     cotton

tblProducts

ProductID|type  |method|
 2222     cotton  first
 2223     cotton  first

预期结果:

ProductID|type  |method|
 2222     cotton  first
 2223     cotton  first
 2224     cotton  first
 2225     cotton  first

我希望这有意义,我想根据数量值

添加或删除行

1 个答案:

答案 0 :(得分:0)

尝试以下代码,如果您遇到任何问题,请告诉我

begin

  DECLARE @visitid INTEGER;
  DECLARE @quantity INTEGER;
  DECLARE @type VARCHAR(100);
  DECLARE @productid INTEGER;
  DECLARE @method VARCHAR(100);
  DECLARE @diff NUMERIC;
  DECLARE @CNT INTEGER;

 with temp as 
 (
  select type,count(1) as cnt 
  from tblproducts
  group by type
 )
select s.visitid,s.quantity,s.type,p.productid,p.method,temp.cnt as cnt  
 into #tempor
from tblshipment s join tblproducts p
on s.type=p.type 
inner join temp on 
s.type=temp.type 
and s.quantity <> temp.cnt 

declare productcursor cursor for select 
visitid,quantity,type,productid,method,cnt 
from #tempor 

open productcursor

 fetch next from productcursor into 
 @visitid,@quantity,@type,@productid,@method,@cnt

while (@@FETCH_STATUS <> -1)
 BEGIN 
   declare @i integer;
  set @i=1;
 if (@Quantity-@cnt) > 0 
  BEGIN
       while (@i < (@Quantity-@cnt) ) 
       BEGIN 
           insert into tblproducts SELECT max(productid) + 1 AS 
           PRODCUTID,type AS TYPE,method AS METHOD
           from tblproducts t 
           where type=@type and method=@method group by type,method 

          SET @i = @i+1;   
        END     
       fetch next from productcursor into 
    @visitid,@quantity,@type,@productid,@method,@cnt ;
   END 
  ELSE IF (@quantity-@cnt) <0 
   BEGIN
        while (@i <= (@cnt-@quantity))
       BEGIN             
           select *,
           row_number() over(partition by type,method order by productid 
            desc) as rn 
           into #del
           from tblproducts     

           delete from tblproducts 
           where productid in (select productid from #del where rn <=(@cnt-
            @quantity))
           and type=@type and method=@method
           SET @i = @i+1; 
        END
        fetch next from productcursor into 
        @visitid,@quantity,@type,@productid,@method,@cnt ;
     END
  END   

  close productcursor
  deallocate productcursor ;
 END