将动态JOINS转换为SQL语句

时间:2011-06-10 07:33:25

标签: sql

我需要一个想法,将以下“If”的条件转换为原始SQL语句。 (无动态SQL)

Dim strVar1 as String, strVar2 as String, strVar3 as String, intSet Int32

.Append("SELECT * FROM TABLE_A as A ")
.Append("INNER JOIN TABLE_B as B ON A.Code=B.Code_A ")

If strVar1.Length > 0 Then
  .Append("LEFT JOIN TABLE_C as C ON C.Code=A.Code_C ")
  .Append("LEFT OUTER JOIN TABLE_D as D on C.Code=D.Code_C AND D.Col1 IN (1,NULL) ")
End If

If strVar2.Length > 0 Or strVar3.Length > 0 Then
  .Append("LEFT OUTER JOIN TABLE_E as E ON A.Code=E.Code_A ")
  .Append("LEFT OUTER JOIN TABLE_F as F ON E.Col1=F.Col1 ")
  .Append("INNER JOIN TABLE_G ON as G ON F.Code=G.Code_F AND G.Col1=1 ")
End If

Select Case intType
    Case 1 , 2    
       If intSet <> -1 Then
         .Append("LEFT OUTER JOIN TABLE_H H on A.code=H.code_A AND H.code_H=1 AND H.Pos=1 ")
       Else
         .Append("LEFT OUTER JOIN TABLE_H H on A.code=H.code_A AND H.Pos=1 ")
       End If
    Case 3 , 4
End Select

2 个答案:

答案 0 :(得分:0)

您可以尝试SQL构造! 逻辑:所有联接都将在那里。但是,如果要根据某些条件加入,请将join表中的cross table列放在同一个表列中 类似的东西:

 SELECT DISTINCT TABLE_A.* FROM TABLE_A as A
INNER JOIN TABLE_B as B ON A.Code=B.Code_A
LEFT JOIN TABLE_C as C ON C.Code=
    CASE WHEN LEN(@strVar1)>0
    THEN
    A.Code_C -- join with your table
    ELSE
    C.Code -- join with itself to do nothing
    END
LEFT OUTER JOIN TABLE_D as D on C.Code=
    CASE WHEN LEN(@strVar1)>0 THEN
    D.Code_C AND D.Col1 IN (1,null)
    ELSE
    C.Code
    END

等等

答案 1 :(得分:0)

我不确定将动态sql代码转换为带参数的单个sql查询很容易,甚至可能。我觉得唯一的解决方案是为您在测试中使用的每个值组合创建一个查询。这是很多疑问:16如果我算得正确的话。

如果您的目标是加快查询速度,我很确定这会有所帮助:每次都不需要计算执行计划。但这是以更复杂的代码为代价的。