1、数据库中的临时表有两种形式
a.以变量的形式
eg. declare @stock table(id int ,num decimal(10,2)) --创建变量
insert @stock select 1,100 --使用变量
b.就是临时表名前加# 号的
eg. create table #temp
(
id int
)
二者的区别:变量的形式运行一次就没有了,相当于开发程序中的临时变量。
#号的其实是存储在系统数据库中的tempdp这个临时库里,相当于存储在一个会话状态里,如果会话结束临时表也就随之消失了。
2、一个例子:
有以下3个表:
--期库
declare @stock table(id int ,num decimal(10,2))
insert @stock select 1,100
union all select 3,500
union all select 4,800
--入库
declare @in table(id int,num decimal(10,2))
insert @in select 1,100
union all select 1,80
union all select 2,800
--出库
declare @out table(id int,num decimal(10,2))
insert @out select 2,100
union all select 3,100
union all select 3,200
实现这个效果
具体代码:
select id,sum(stock_opening) stock_opening,sum(stock_in) stock_in,sum(stock_out) stock_out,sum(stock_closing) stock_closing from
(select id ,num as stock_opening ,0 as stock_in ,0 as stock_out,num stock_closing from @stock
union all
select id,0 as stock_opening,num as stock_in,0 as stock_out,num stock_closing from @in
union all
select id,0 as stock_opening,0 as stock_in,num as stock_0ut,num stock_closing from @out)as a
group by id