摘要:stored procedure(預存程序的範例)
最近都在寫db這邊的東西,把範例貼出來,以便以後如果要使用的話,可以有樣本可以看一下
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE sp_min0206
(
@icompid nvarchar(10), @iyymm nvarchar(10) --要傳進來的參數
)
AS
declare @t_uniprice decimal(15,4)
declare @t_count int
declare @codebsi nvarchar(10)
--定義變數都一定要給@,不然會出錯,nvarchar一定得要給數值,空白的話值都只會變成一碼,我遇到的情形是這樣
declare @queue_emp TABLE
(
productid nvarchar(20) null,
hid nvarchar(20) null,
codebsi nvarchar(10) null,
qty decimal(15,4) default 0,
porder int default 0
)
--定義一個暫存的table
set @t_enddate = @iyymm + '/31'
select @t_codecost=minno01 from actpa
--上面兩個都是把後面的值給前面的變數
insert into @queue_emp
select productid,hid,codebsi,qty,0
from bmipackh
--把值寫進tem table
select top 1 @t_productid=productid,@t_hid=hid,@t_hqty=qty
from @queue_emp
order by porder,codebsi
while(@@ROWCOUNT=0)
begin
set @t_bommode = '1'
end
--只選出一筆,所以用上面的方式寫
--下面一整段則是要撈資料跑迴圈的寫法
declare myrowrecord cursor static for --把值select出來塞進cursor
select b.matid,b.qty,m.codebsi,b.bodyno,b.uniprice
from bmipackb b
left join material m on m.matid = b.matid
open myrowrecord
fetch next from myrowrecord into @matid,@qty,@codebsi,@bodyno,@uniprice --再把值into進去自定義的變數裡
while(@@FETCH_STATUS=0) --然後while迴圈,必須都要begin然後再end
begin
set @t_count = 0
if @codebsi = 'b' --if也一樣,都要begin然後再end
begin
select @t_count=count(*) from @queue_emp
where productid = @matid
end
fetch next from myrowrecord into @matid,@qty,@codebsi,@bodyno,@uniprice --這邊就是把上面的copy過來,沒寫的話會造成無窮迴圈
end
close myrowrecord
deallocate myrowrecord
--上面一整段則是要撈資料跑迴圈的寫法