一、 临时表
1.临时表的基础操作
--1.设置临时表(常用)
SELECT * INTO #temp from ( 你的表 )
--2.清空临时表中的数据
TRUNCATE TABLE #temp
--3.删除临时表
DROP TABLE #temp
1.创建临时表
create table #临时表名(字段1 约束条件,字段2 约束条件,
.....)
create table ##临时表名(字段1 约束条件,字段2 约束条件,
.....)
select * into #临时表名 from 你的表
select * into ##临时表名 from 你的表
'PS:以上的#代表局部临时表,##代表全局临时表'
三、游标查询实例
单号 |
渠道号 |
国家 |
重量 |
入库时间 |
出库时间 |
起飞时间 |
到达目的地时间 |
妥投时间 |
入库至出库时间 |
入库至起飞时间 |
入库至到达目的地时间 |
入库至妥投时间 |
WI00172414127SH |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
- 表temp_1.dbo.aaa为存放结果表
- 表#temp2为数据临时表
- 需要调用数据并且行转列
DROP TABLE #temp2 ---清空临时表
truncate table temp_1.dbo.aaa ---清空结果临时表
----通过连表查出barcode单号对应的pushdate时间和trackname状态----
select * into #temp2 from (
SELECT b.tracking_id barcode,a.pushdate,a.trackname
FROM syncdatas.dbo.tracking_log3 a
inner join [temp_1].[dbo].[3PL-Wish达] b --更换表格名称
on a.barcode = b.tracking_id
where trackname in('ARRIVE_FIRST_MILE','DEPART_FIRST_MILE','DEPART_AIRPORT','ARRIVE_DEST_AIRPORT','DELIVERED')
)c
---select * from #temp2
--查询barcode单号赋值取游标
declare my_cursor Cursor Scroll for select tracking_id from [temp_1].[dbo].[3PL-Wish达] --更换表格
declare @barcode varchar(50)
declare @country varchar(50)
declare @weight numeric(18, 4)
declare @index int=0
open my_cursor --开始游标
fetch next from my_cursor into @barcode --下一条游标赋值
while(@@Fetch_Status = 0) --循环
begin
set @index=@index+1
--取出国家
set @country=(select a.收件地 from (select 单号,收件地,重量 from [46].[express_45].[dbo].[bill_2020]
union select 单号,收件地,重量 from [46].[express_45].[dbo].[bill_2021]) as a
inner join temp_1.dbo.[3PL-Wish达] b --更换表格
on a.单号=b.tracking_id where b.tracking_id=@barcode)
--取出重量
set @weight=(select a.重量 from (select 单号,收件地,重量 from [46].[express_45].[dbo].[bill_2020]
union select 单号,收件地,重量 from [46].[express_45].[dbo].[bill_2021]) as a
inner join temp_1.dbo.[3PL-Wish达] b --更换表格
on a.单号=b.tracking_id where b.tracking_id=@barcode)
--行转列,把状态对应的时间插入到新表格。
insert into [temp_1].[dbo].[aaa](单号,国家,重量,入库时间,出库时间,起飞时间,到达目的地时间,妥投时间) values(@barcode,@country,@weight,
(select top 1 pushdate from #temp2 where trackname='ARRIVE_FIRST_MILE' and barcode=@barcode),
(select top 1 pushdate from #temp2 where trackname='DEPART_FIRST_MILE' and barcode=@barcode),
(select top 1 pushdate from #temp2 where trackname='DEPART_AIRPORT' and barcode=@barcode),
(select top 1 pushdate from #temp2 where trackname='ARRIVE_DEST_AIRPORT' and barcode=@barcode),
(select top 1 pushdate from #temp2 where trackname='DELIVERED' and barcode=@barcode)
)
fetch next from my_cursor into @barcode --游标赋值循环下一条
end
close my_cursor --关闭游标
deallocate my_cursor --释放游标
print @index
Copyright © 2009 - Now . XPBag.com . All rights Reserved.
夜心的小站 »
特殊的常用SQL语句及用法、游标、存储过程等