我在criteria
表的记录中保存了标准,我用它来创建一个动态查询字符串,该字符串将查询source
表,并将该查询的结果插入到destination
表。我的目标是,如果条件与criteria
表中的记录匹配,也会将destination
表中的id插入source
表。如果匹配了多个条件记录,我只需插入第一个条件。
WHERE子句是通过 OR'ing 将多个部分组合在一起构建的,并且每个部分内的条件都是 AND'ed 。如下所示:
insert into destinationTable(col1, col2, col3)
select col1, col2, col3
from sourceTable
where
--' begin generated code'
(a = 525 and b = 324 and c = 4523) -- 'from criteria record 1'
or (d = 'asdf' and e = 3.43) -- 'from criteria record 2'
or (f = 234523 and g = 9823742) -- 'from criteria record 3'
etc...
--' end generated code'
我需要找到一种方法来确定哪个是匹配条件的第一个OR部分,并在目标表中插入相应的条件id如何做到这一点?
答案 0 :(得分:7)
您可以在Select子句中包含一个case语句,该语句将输出成功的第一个OR子句:
Select ...
, Case
When a = 525 And b = 324 And C = 4523 Then Criteria_Row_1_Pk
When d = 'asdf' and e = 3.43 Then Criteria_Row_2_Pk
....
End As SuccessClausePk
答案 1 :(得分:4)
将union替换为union,并添加一个给出标准号
的列select col1, col2, col3, 1
from sourceTable
where
--' begin generated code'
(a = 525 and b = 324 and c = 4523) -- 'from criteria record 1'
union all
select col1, col2, col3, 2
from sourceTable
where (d = 'asdf' and e = 3.43) -- 'from criteria record 2'
union all
select col1, col2, col3, 3
from sourceTable
where (f = 234523 and g = 9823742) -- 'from criteria record 3'
etc...
答案 2 :(得分:2)
除非可能存在可以提供所涉及的所有列的索引,否则表可能会被完全扫描。由于我们正在浏览所有记录,因此您也可以执行之前的确定过滤。
SELECT col1, col2, col3, Which
FROM
(
select col1, col2, col3,
CASE
--' begin generated code'
WHEN
(a = 525 and b = 324 and c = 4523) -- 'from criteria record 1'
THEN 1
WHEN
(d = 'asdf' and e = 3.43) -- 'from criteria record 2'
THEN 2
WHEN
(f = 234523 and g = 9823742) -- 'from criteria record 3'
THEN 3
--' end generated code'
END Which
from sourceTable
) SQ
WHERE Which is not null -- remove where it didn't match any criteria
表单可预测且足够一致,足以代码生成友好