(转)联合删除两张表的数据
大家都知道DELETE后面不能跟多张表,但有时删除数据时要同时维护多张表的数据,这怎么办呢?
假设:A,B两张表,它们通过ID进行关联,A表中有时间字段而B表中没有,现根据时间段删除数据
SQL:
假设:A,B两张表,它们通过ID进行关联,A表中有时间字段而B表中没有,现根据时间段删除数据
SQL:
Declare @DelID Table(ID int)
Delete A
Output Deleted.ID
Into @DelID
From A
Inner Join B ON A.ID=B.ID
Where A.dt>='2007-11-1' And A.dt<='2007-11-2'
Delete B Where ID In(Select ID From @DelID)
Delete A
Output Deleted.ID
Into @DelID
From A
Inner Join B ON A.ID=B.ID
Where A.dt>='2007-11-1' And A.dt<='2007-11-2'
Delete B Where ID In(Select ID From @DelID)
注:这是MSSQL2005的新语法:Delete Into