我希望能够使用varable表从两个不同的表中删除记录。
到目前为止我有这个
declare @deleted TABLE (Card int)
insert into @deleted
select Card from table1
where recordstatus = 4
delete from table2
from @deleted d
where table2.actionstring like d.card
and Select convert(varchar(8),today,112)
from(Select dateadd(year,-1,getdate())as today)aa
抱歉,如果这令人困惑,我使用的是sql管理2005
我基本上希望能够从表1中获取卡号,检查表2中的日期是否大于一年,如果是,则删除表1中的记录。
在表2中,我没有卡号的字段,所以我需要一个LIKE语句。
我在第二部分中只有一个错误,其中包含: 来自@deleted d
提前谢谢
答案 0 :(得分:1)
你的陈述的第二部分确实令人困惑....你在WHERE子句中混合DELETE和SELECT .....你想在这里实现什么? ?
declare @deleted TABLE (Card int)
insert into @deleted
select Card from table1
where recordstatus = 4
delete table2
from @deleted d
where table2.actionstring LIKE '%' + CAST(d.card AS VARCHAR(20)) + '%'
and CONVERT(DATETIME, table2.Date, 112) <= DATEADD(YEAR, -1, GETDATE())
delete table1
from @deleted d
where table1.card = d.card
and CONVERT(DATETIME, table1.Date, 112) <= DATEADD(YEAR, -1, GETDATE())
您是否尝试删除table2
中Table2.ActionString
等于Card
表中@deleted
列的所有行?不太清楚。
另外:日期约束是什么? table2
中的哪个字段要检查?条件是什么 - <=
或>=
或什么?
答案 1 :(得分:1)
DELETE table1
FROM table1 INNER JOIN
table2 ON table1.card = table2.actionstring
WHERE table1.recordstatus = 4 AND
table2.SomeDateColumn >= DATEADD(year, -1, GETDATE())
答案 2 :(得分:0)
尝试类似:
delete t1
from
table1 t1
join table2 t2
on t2.actionstring like t1.card + '%'
and [... other criteria ...]
答案 3 :(得分:0)
table2
没有密钥的事实使事情变得复杂。特别是在这种情况下,我无法看到如何避免在table2
中重复搜索。
无论如何,这里是:
DECLARE @deleted TABLE (card int);
/* store cards that are actually going to be deleted */
INSERT INTO @deleted (card)
SELECT DISTINCT t1.card
FROM table1 t1
INNER JOIN table2 t2 ON t2.Date <= DATEADD(year, -1, GETDATE())
AND t2.actionstring LIKE '%' + RIGHT(100000000 + t1.card, 8) + '%'
WHERE t1.recordstatus = 4
/* delete the history for the selected cards */
DELETE FROM t2
FROM @deleted t1
INNER JOIN table2 t2 ON t2.Date <= DATEADD(year, -1, GETDATE())
AND t2.actionstring LIKE '%' + RIGHT(100000000 + t1.card, 8) + '%'
/* delete the cards from table1 */
DELETE FROM table1
FROM @deleted d
WHERE table1.card = d.card
AND table1.recordstatus = 4 /* not sure if this condition is needed again
but it will certainly do no harm */