Edd*_*die 3 sql sql-server-2012
我想从每个删除语句的相同条件(where子句)的多个表中删除数据.
delete from tblA where id in (select x.id from tblX x where name like N'%test%')
delete from tblB where id in (select x.id from tblX x where name like N'%test%')
delete from tblC where id in (select x.id from tblX x where name like N'%test%')
delete from tblD where id in (select x.id from tblX x where name like N'%test%')
Run Code Online (Sandbox Code Playgroud)
有没有办法声明一个列表来存储上面的select语句中的id?
我试过了:
declare @ids int
set @ids = select x.id from tblX x where name like N'%test%'
Run Code Online (Sandbox Code Playgroud)
但它抱怨说
子查询返回的值超过1.当子查询跟随=,!=,<,<=,>,> =或子查询用作表达式时,不允许这样做.
请指教,谢谢.
lol*_*lol 10
无论如何你都需要一张桌子,但至少你每次都做类似的事情就避免了大量的处理:
-- create a table variable
declare @ids table
(
id int not null
)
-- insert the id into the table variable
insert into @ids
select id from table1 where column1 like '%something%'
-- delete
delete from tablen where id in (select * from @ids)
Run Code Online (Sandbox Code Playgroud)
您也可以使用临时表,它看起来是一样的,但不是@ids,而是需要#ids,并且您需要在作业完成后删除临时表.
要在临时表(物理表)或表变量(像表这样的内存)之间进行选择,您确实需要进行一些测试,但根据定义,复杂数据在临时表中的效果更好.如果您只需要在短时间内保留少量ID,我非常确定表变量更好.
| 归档时间: |
|
| 查看次数: |
25361 次 |
| 最近记录: |