1游标实现
三张 关联的表 的游标操作
at 字段 AID ANAME
bt 字段 BID BNAME AID
ct 字段 CID CNAME BID
通过循环读取at中的id 更新bt中的name 再根据bt中id循环更新ct中的name
--SET NOCOUNT ON 显示受影响的行数
DECLARE @AID INT
DECLARE @BID INT
DECLARE publish_cursor CURSOR FOR
SELECT Aid FROM aT
OPEN publish_cursor
FETCH NEXT FROM publish_cursor
INTO @AID
WHILE @@FETCH_STATUS = 0
BEGIN
print @AID
--修改记录
update BT set BNAME=GETDATE() where Aid=@Aid
DECLARE publish_cursor2 CURSOR FOR
SELECT Bid FROM BT
OPEN publish_cursor2
FETCH NEXT FROM publish_cursor2
INTO @BID
print @BID
update CT set CNAME=GETDATE() where Bid=@Bid
--修改结束
FETCH NEXT FROM publish_cursor2 into @Bid
CLOSE publish_cursor2
DEALLOCATE publish_cursor2
--修改结束
FETCH NEXT FROM publish_cursor into @Aid
END
CLOSE publish_cursor
DEALLOCATE publish_cursor
GO
2用CTE实现 WITH(但是他只能对紧接着的sql语句有效,所以只能执行一部操作)
;WITH atInfo as (SELECT * FROM aT where aid=1),
btInfo as (SELECT * FROM bT where bid in (select AID from atInfo))
-- Update BT set bName = 'WITH' WHERE AID in (select AID from atInfo)
Update cT set cName = 'WITHc' WHERE bID in (select bID from btInfo);
select * from ct;