2017-08-01 137 views
-1

我有一個非常複雜的問題。任何人都可以給我任何方向爲以下情況,根據另一個表中的字段從表中插入或刪除行

我有兩個表。 tblone,tbltwo。我想根據tblone中的數量值在tbltwo中插入或刪除記錄。例如,如果tbl.Quantity是4並且在tbltwo中有2行,那麼我需要添加兩行。如果tbl.Quantity是1,tbltwo有3行,我想刪除2行。我很困惑。任何幫助表示讚賞。我嘗試用遊標,但沒有成功。

SELECT Quantity 
FROM tblOrder 
WHERE visitid = 123123 

結果是4

​​

結果爲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

顯示數據和什麼標準決定刪除將有所幫助。我希望。另外,顯示你的嘗試。 –

+1

所以它看起來像'tblone'中的'Quantity'將決定'tbltwo'中應該有多少行。那是對的嗎? –

+0

['MERGE'](https://docs.microsoft.com/zh-cn/sql/t-sql/statements/merge-transact-sql)是[SAK](http://www.sakwiki.com) /tiki-index.php)的語句。它也可以是TSQL的正則表達式:現在你有兩個問題。 – HABO

回答

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 (@[email protected]) > 0 
    BEGIN 
     while (@i < (@[email protected])) 
     BEGIN 
      insert into tblproducts SELECT max(productid) + 1 AS 
      PRODCUTID,type AS TYPE,method AS METHOD 
      from tblproducts t 
      where [email protected] and [email protected] group by type,method 

      SET @i = @i+1; 
     END  
     fetch next from productcursor into 
    @visitid,@quantity,@type,@productid,@method,@cnt ; 
    END 
    ELSE IF (@[email protected]) <0 
    BEGIN 
     while (@i <= (@[email protected])) 
     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 [email protected] and method[email protected] 
      SET @i = @i+1; 
     END 
     fetch next from productcursor into 
     @visitid,@quantity,@type,@productid,@method,@cnt ; 
    END 
    END 

    close productcursor 
    deallocate productcursor ; 
END 
+0

如果Productid是標識列,則請執行更改以反映通過從插入中刪除產品 – Aparna

相關問題