如何使用Sql Server 2008重构具有子查询的select语句?

时间:2012-10-09 07:02:38

标签: sql sql-server sql-server-2008 refactoring

有时,子查询很好并且有它们的位置,如以下代码所示:

select x1.test, (select r from table) from ......

但是,添加更多子查询会在查询中产生更多障碍,例如性能问题和可重用性问题,仅举几例/

我如何重构下面的sql代码以使其比以前更快地运行...



Select f.c1
      ,f.c2
         ,f.c3 As 'c3Id'
         ,p.Value As 'c3'
         ,m.c4 As 'r1'


         ,(Select SUM(t1.table1x)
             From [ap].table1 t1
             Where t1.table1x = 1 
               And f.c1 = t1.c1 
               And f.c2 = t1.c2
               And f.c3 = t1.c3) As 'r2'

         ,(Select SUM(t2.x)
             From [ap].table2 t2
             Where t2.c1 = f.c1
               And t2.c1 = f.c2
               And t2.c3 = f.c3) As 'r3'

         ,(Select SUM(t1.table1x)
             From [ap].table3 t3
             Where t3.table3Turu = 2
               And f.c1 = t3.c1 
               And f.c2 = t3.c2
               And f.c3 = t3.c3) As 'r4'

         ,(Select SUM(t4.x)
             From [ap].table4 t4
             Where t4.c1 = f.c1
               And t4.c1 = f.c2
               And t4.c3 = f.c3) As 'r5'

From [ap].table1 f 
Inner Join [dbo].table5 m On f.c1 = m.col11
Inner Join [dbo].table6 p On f.c3 = p.col22

Where p.xxxx = 'test'
Group By f.c1, f.c2, f.c3, m.c4, p.Value

1 个答案:

答案 0 :(得分:0)

您可以使用UDF(用户定义函数)来简化代码。将子查询包含在函数中,并从主查询中将所需参数发送到此函数。例如,您可以将3个参数f.c1,f.c2和f.c3发送到一个函数,例如GetSumT1(),并在查询中使用它来代替您的子查询。

Select f.c1       
,f.c2          
,f.c3 As 'c3Id'          
,p.Value As 'c3'          
,m.c4 As 'r1'            
, GetSumT1(f.c1, f.c2, f.c3) As 'r2'
...
...