我有以下SQL代码来执行清理任务:
SELECT
第一个 n - 来自满足条件的表并将它们放在一个新表中。请注意,[source].var='1'
因不同的表而异。
SELECT TOP n * INTO tablen
FROM source
WHERE [source].var='1';
# concrete example
SELECT TOP n * INTO table1
FROM source
WHERE [source].var1='1';
SELECT TOP n * INTO table2
FROM source
WHERE [source].var2='1';
SELECT TOP n * INTO table3
FROM source
WHERE [source].var3='1';
SELECT TOP n * INTO table4
FROM source
WHERE [source].var4='1';
SELECT TOP n * INTO table5
FROM source
WHERE [source].var5='1';
从第一步开始 n -tables后,我使用查询连接它们。
# code2
SELECT * FROM table1
UNION ALL
SELECT * FROM table2
UNION ALL
SELECT * FROM table3
UNION ALL
SELECT * FROM table4
UNION ALL
SELECT * FROM table5
最后,我将第二个结果放入一个新表中,以便我可以使用它。
SELECT *
INTO dest
FROM code2
有谁知道如何将这些乏味的任务放入一个SQL查询中,这样我就不必重复15次了?
答案 0 :(得分:0)
我试着回答这个问题,但这是我的第一个答案,所以对我很轻松。首先,我不确定每个“TOP”行查询的源表是否相同。如果它是那么你不需要表,1-5。当然,除非你出于某种原因想要5个临时表...我想你知道你在UNION ALL做了什么。
只需查询内联原始表:
select a.* into dest
from (select TOP n *
from source
where source.var1='1'
UNION ALL
select TOP n *
from source
where source.var2='1'
UNION ALL
select TOP n *
from source
where source.var3='1'
UNION ALL
select TOP n *
from source
where source.var4='1'
UNION ALL
select TOP n *
from source
where source.var5='1'
) a