更新#table并插入

时间:2018-06-15 04:27:29

标签: sql-server

我正在创建游标

declare @Code varchar(max)
declare @whs varchar(max)
declare @whsName varchar(max)
declare @qty float
declare @Name varchar(max)
declare @width varchar(max)
declare @length varchar(max)
declare @hight varchar(max)
declare @Uom varchar(max)




DECLARE Receipt CURSOR
      KEYSET
      FOR   

      select a.ItemCode,a.whscode,c.whsname, a.onhand,b.ItemName,b.U_Width_UOM,b.U_Length_UOM,b.U_Height_UOM,b.invntryuom

from oitw a inner join oitm b on a.itemcode=b.itemcode inner join owhs c on c.whscode=a.whscode

where a.onhand >0 


      Open Receipt

      FETCH FIRST FROM Receipt INTO @Code,@whs,@whsName,@qty,@Name,@width,@length,@hight,@Uom
WHILE @@FETCH_STATUS=0

begin



update #Items
--I am updating the existing stock
            set StockInWhs=@qty where ItemCode=@Code and WhsCode=@whs 


      --and also i need to enter the stock data in to following #table if the stock not update as above.

            insert into #Items 

            (ItemCode ,
ItemName ,
U_Width_UOM ,
U_Length_UOM ,
U_Height_UOM ,

invntryuom ,
StockInWhs ,
WhsName ,
WhsCode )

Values (@Code,@Name,@width,@length,@hight,@Uom,@qty,@whsName,@whs)


FETCH Next FROM Receipt INTO @Code,@whs,@whsName,@qty,@Name,@width,@length,@hight,@Uom

end
end

CLOSE  Receipt
DEALLOCATE Receipt

1 个答案:

答案 0 :(得分:0)

使用If Exists函数尝试使用Loop而不是Cursor,因为光标很慢。

BEGIN TRAN

declare @Code varchar(max)
declare @whs varchar(max)
declare @whsName varchar(max)
declare @qty float
declare @Name varchar(max)
declare @width varchar(max)
declare @length varchar(max)
declare @hight varchar(max)
declare @Uom varchar(max)
Declare @strt INT
DECLARE @End INT



select a.ItemCode,a.whscode,c.whsname, a.onhand,b.ItemName,b.U_Width_UOM,b.U_Length_UOM,b.U_Height_UOM,b.invntryuom,ROW_NUMBER()OVER(Order by a.ItemCode)rownum  INTO #T
from oitw a inner join oitm b on a.itemcode=b.itemcode inner join owhs c on c.whscode=a.whscode
where a.onhand >0 

SET @strt=1
SELECT @End=MAX(rownum) FROM #T

WHile @strt <=@End  BEGIN

        SELECT @Code= ItemCode,@whs=whscode,@whsName=whsname,@qty =onhand, @Name=ItemName,@width=U_Width_UOM,
                @length=U_Length_UOM,@hight=U_Height_UOM,@Uom=invntryuom 
        FROM #T WHERE rownum= @strt

        IF Exists (SELECT 1 FROM Table_Name  where ItemCode=@Code and WhsCode=@whs ) BEGIN

                    /*Update the existing stock as follows*/
                        update #Items set StockInWhs=@qty where ItemCode=@Code and WhsCode=@whs 

        END ELSE BEGIN
                   insert into #Items (ItemCode ,ItemName ,U_Width_UOM ,U_Length_UOM ,U_Height_UOM ,invntryuom ,StockInWhs ,WhsName ,WhsCode )
                    SELECT  (@Code,@Name,@width,@length,@hight,@Uom,@qty,@whsName,@whs)
        END

        SET @strt= @strt+1

END

ROLLBACK TRAN