TSQL针对多个嵌套案例查询进行优化

时间:2017-01-12 02:27:46

标签: sql-server tsql

有人可以帮我优化此查询。我只写出了两个案例陈述,但它实际上有30个这样的案例都嵌套在下面的例子中(见2)。

import UIKit
import PlaygroundSupport

let image = #imageLiteral(resourceName: "image.png")
let celSize = CGSize(width: image.size.width / 3, height: image.size.height)
let imageView = UIImageView()
imageView.frame = CGRect(origin: .zero, size: celSize)
imageView.image = image

PlaygroundPage.current.liveView = imageView

let animation = CAKeyframeAnimation(keyPath: "contentsRect")
animation.duration = 1.5
animation.calculationMode = kCAAnimationDiscrete
animation.repeatCount = .infinity
animation.values = [
    CGRect(x: 0, y: 0, width: 1/3.0, height: 1),
    CGRect(x: 1/3.0, y: 0, width: 1/3.0, height: 1),
    CGRect(x: 2/3.0, y: 0, width: 1/3.0, height: 1)
] as [CGRect]
imageView.layer.add(animation, forKey: animation.keyPath!)

2 个答案:

答案 0 :(得分:0)

这是非常糟糕的SQL代码,因为数据库引擎根本不能进行任何优化,因为它需要枚举整个表并按记录进行记录,每次执行多次测试,两次。

您可以在没有任何CASE的情况下执行此操作:

SELECT *
FROM QS
INNER JOIN R ON (   (R.FieldCode = 'L'
                     AND (   (R.Match = 1 AND QS.lineid IN (SELECT CONVERT(int,s) FROM SplitFunc(',', R.FieldValue)))
                          OR (R.Match = 0 AND QS.lineid NOT IN (SELECT CONVERT(int,s) FROM SplitFunc(',', R.FieldValue)))))
                 OR (R.FieldCode = 'D'
                     AND (   (R.Match = 1 AND QS.productid IN (SELECT CONVERT(int,s) FROM SplitFunc(',', R.FieldValue)))
                          OR (R.Match = 0 AND QS.productid NOT IN (SELECT CONVERT(int,s) FROM SplitFunc(',', R.FieldValue)))))                 
                )

答案 1 :(得分:0)

这对您来说效果更好吗?不知道相对行数或基础数据,我认为这可能会更快,更容易维护,因为你不必一遍又一遍地运行标量函数,而且应该更加优化。

SELECT * -- Change to only get fields you need from QS.*
FROM (
    SELECT
        QS.*,
        ',' + CONVERT(VARCHAR(10),
            CASE R.FieldCode
                WHEN 'L' THEN QA.lineid
                WHEN 'D' THEN QA.productid
                -- ...
                END + ',' AS MatchValue,
        ',' + R.FieldValue + ',' AS FieldValueCSV
        R.Match
    FROM QS 
        CROSS JOIN R
    ) T
WHERE (T.Match = 1 AND T.FieldValueCSV LIKE '%' + T.MatchValue + '%')
    OR (T.Match = 0 AND NOT T.FieldValueCSV LIKE '%' + T.MatchValue + '%')