“在ident_key = null上保留连接表”会帮助查询速度吗?

时间:2018-05-05 09:58:47

标签: sql sql-server sql-server-2012 query-optimization

有三个表,两个上游table A and B和一个下游table Ctable A and B中的记录将被处理并合并到table C

Table A ( id_a identity not null, prop, val )
Table B ( id_b identity not null, prop, val )
Table C ( id_c, 
    original_id [id_a or id_c],
    prop, processed_val, 
    source_table [ 'A' or 'B' ] )
NOTE: id_a and id_b has different format they never collide.

我需要更正某些应用行为,而无需访问应用代码。因此,我尝试在table C上附加触发器,并根据原始数据操纵process_val

我能做到

UPDATE C 
SET processed_value = NEW_FUNCTION( coalesce(A.val,B.val) )
FROM inserted
LEFT JOIN A ON ( C.orginal_id = A.id )
LEFT JOIN B ON ( C.orginal_id = B.id )

但我认为在返回resut之前必须经过两个表索引。我不想使用动态查询,我希望将其作为一个sql过程保持简单。

我想知道下面的某些内容是否有助于阻止redunant查找,因为这些密钥不应该是NULLNULL值是否会停止查找?

UPDATE C 
SET processed_value = NEW_FUNCTION( coalesce(A.val,B.val) )
FROM inserted
LEFT JOIN A ON ( A.id = case when source_table='A' then C.orginal_id else NULL end )
LEFT JOIN B ON ( B.id = case when source_table='B' then C.orginal_id else NULL end )

或者MSSQL中有没有其他方法可以动态切换源表(没有动态查询)?

1 个答案:

答案 0 :(得分:0)

我认为您需要JOINC之间的inserted。我希望逻辑看起来更像这样:

UPDATE C 
    SET processed_value = NEW_FUNCTION(coalesce(A.val, B.val))
    FROM inserted i JOIN
         C
         ON i.id_c = C.id_C LEFT JOIN
         A
         ON A.id = i.original_id AND i.source_table = 'A' LEFT JOIN
         B
         ON B.id = C.orginal_id AND i.source_table = 'B';