可參考(以下代碼自己寫個存儲過程):
if exists (select name from sysobjects where name='st_in') drop table st_in
create table St_in /*進貨表*/
(
inv_no varchar(30),/*產品編號*/
op_date datetime,/*進貨日期*/
quan float,/*數量*/
primary key(inv_no,op_date)
)
if exists (select name from sysobjects where name='st_out') drop table st_out
create table St_out
(
inv_no varchar(30),/*產品編號*/
op_date datetime,/*出貨日期*/
quan float,/*數量*/
primary key(inv_no,op_date)
)
if exists (select name from sysobjects where name='st_end') drop table st_end
create table st_end /*結存表*/
(
inv_no varchar(30), /*產品編號*/
quan_in float, /*本用進貨數量*/
quan_out float, /*本用出貨數量*/
primary key(inv_no)
)
declare @date1 varchar(7)
/*格式2001-04*/
select @date1='2001-01' /*你可輸入查詢的月份,應加上年份*/
delete from st_end
insert st_end (inv_no,quan_in,quan_out) select inv_no,sum(quan),0 from st_in
where left(convert(varchar(10),op_date,20),7)=@date1 group by inv_no
update st_end set quan_out=(select isnull(sum(quan),0) from st_out
where left(convert(varchar(10),op_date,20),7)=@date1 and st_out.inv_no=st_end.
inv_no)
insert st_end (inv_no,quan_in,quan_out) select inv_no,0,sum(quan) from st_out
where left(convert(varchar(10),op_date,20),7)=@date1 and inv_no not in
(select inv_no from st_in where left(convert(varchar(10),op_date,20),7)=@date1)
group by inv_no
在SqlServer調試下通過。