求帮忙存储过程
表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