首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求帮忙存储过程解决思路

2014-01-12 
求帮忙存储过程表AOIDTIDCreateTimeAttr1012013-01-02 09:30:08.000Excute2012013-02-02 09:30:08.000Inst

求帮忙存储过程
表A
OID     TID       CreateTime             Attr
1        01    2013-01-02 09:30:08.000   Excute
2        01    2013-02-02 09:30:08.000   Install
3        01    2013-07-02 09:30:08.000   Excute

表B
TID     ConsoleTime    Direction
01       null          into

现在想更新B中的ConsoleTime字段,条件:通过TID查询表A,从得到的查询结果集中筛选CreateTime最小的也就是表A中的第一条记录来更新B中的ConsoleTime
[解决办法]
--先用select *测试看结果
UPDATE b SET b.ConsoleTime=a.minCreateTime 
from 表B b join 
(SELECT MIN(CreateTime) AS minCreateTime ,TID  FROM 表A GROUP BY TID) a
on a.TID=b.TID
[解决办法]


--> 测试数据:表A
if object_id('表A') is not null drop table 表A
go 
create table 表A([OID] int,[TID] varchar(6),[CreateTime] datetime,[Attr]  varchar(10))
insert 表A
select 1,'01','2013-01-02 09:30:08.000','Excute' union all
select 2,'01','2013-02-02 09:30:08.000','Install' union all
select 3,'01','2013-07-02 09:30:08.000','Excute' 

--> 测试数据:表B
if object_id('表B') is not null drop table 表B
go 
create table 表B([TID] varchar(6),[CreateTime] datetime, [Direction]  varchar(10))
insert 表B
select '01',null,'into' 


update a set a.[CreateTime]=b.[CreateTime] from 表B a ,
(
select [TID],min([CreateTime]) as [CreateTime] from 表A group by [TID]
) b
where a.[TID]=b.[TID]

select * from 表B



TID    CreateTime              Direction
------ ----------------------- ----------
01     2013-01-02 09:30:08.000 into

(1 行受影响)
[解决办法]
UPDATE 表b SET CREATETIME = T1.CREATETIME FROM 表b T0,
(SELECT TID,MIN(CREATETIME)CREATETIME FROM 表a GROUP BY TID)t1
WHERE t0.TID = t1.TID
[解决办法]

if  OBJECT_ID('tempdb..#A') is not null drop table #A;
if  OBJECT_ID('tempdb..#B') is not null drop table #B;

create table #A(
OID INT,
TID INT,
CreateTime datetime,
Attr varchar(20)
);
create table #B(
TID INT,
ConsoleTime datetime,
Direction varchar(20)
);
insert into #A 
select 1,01,'2013-01-02 09:30:08.000','Excute' union all
select 2 ,01,'2013-02-02 09:30:08.000', 'Install' union all
select 3, 01,'2013-07-02 09:30:08.000','Excute'

insert into #B
select 01,null,'into' 
 

declare @TID int,@CreateTime datetime
select @TID =TID from #B  --现在B表中只有一条数据,如果有多条数据需要考虑限制条件
select @CreateTime = MIN(CreateTime) from #A where TID = @TID
update #B set ConsoleTime= @CreateTime where TID = @TID
 
select * from #B

drop table #A
drop table #B


TID         ConsoleTime             Direction
----------- ----------------------- --------------------
1           2013-01-02 09:30:08.000 into

(1 行受影响)

热点排行