2

我想在不使用任何 if 语句的情况下重写此代码。

有可能这样做吗?

我如何使用案例或其他东西?

IF @BrandFilter = ''
    BEGIN
        SELECT * FROM
        (
            SELECT
                ROW_NUMBER() OVER(ORDER BY  
                CASE WHEN @SortType = '1' THEN mt.Ad END ASC,
                CASE WHEN @SortType = '2' THEN mt.Ad END DESC,
                CASE WHEN @SortType = '3' THEN mt.Fiyat END ASC,
                CASE WHEN @SortType = '4' THEN mt.Fiyat END DESC) AS RowNr, * 
            FROM @MainTable mt
            WHERE mt.Fiyat > @MinPrice AND mt.Fiyat < @MaxPrice     
        ) Result
        WHERE RowNr > ((@PageNr-1) * 10) AND RowNr <= ((@PageNr) * 10)  
    END
ELSE
    BEGIN
        SELECT * FROM
        (
            SELECT
                ROW_NUMBER() OVER(ORDER BY  
                CASE WHEN @SortType = '1' THEN mt.Ad END ASC,
                CASE WHEN @SortType = '2' THEN mt.Ad END DESC,
                CASE WHEN @SortType = '3' THEN mt.Fiyat END ASC,
                CASE WHEN @SortType = '4' THEN mt.Fiyat END DESC) AS RowNr, * 
            FROM @MainTable mt
            WHERE mt.Fiyat > @MinPrice AND mt.Fiyat < @MaxPrice
            AND mt.MarkaId IN (SELECT bf.Data FROM dbo.Split(@BrandFilter, ',') bf)
        ) Result
        WHERE RowNr > ((@PageNr-1) * 10) AND RowNr <= ((@PageNr) * 10)  
    END

这段代码是不同的,

AND mt.MarkaId IN (SELECT bf.Data FROM dbo.Split(@BrandFilter, ',') bf)

谢谢..

4

2 回答 2

2

干得好:

SELECT * FROM
(
    SELECT
        ROW_NUMBER() OVER(ORDER BY  
        CASE WHEN @SortType = '1' THEN mt.Ad END ASC,
        CASE WHEN @SortType = '2' THEN mt.Ad END DESC,
        CASE WHEN @SortType = '3' THEN mt.Fiyat END ASC,
        CASE WHEN @SortType = '4' THEN mt.Fiyat END DESC) AS RowNr, * 
    FROM @MainTable mt
    WHERE mt.Fiyat > @MinPrice AND mt.Fiyat < @MaxPrice
    AND (@BrandFilter = '' or mt.MarkaId IN (SELECT bf.Data FROM dbo.Split(@BrandFilter, ',') bf))
) Result
WHERE RowNr > ((@PageNr-1) * 10) AND RowNr <= ((@PageNr) * 10)

您必须@brandfilter在拆分之前添加检查是否不为空

(@BrandFilter = '' or mt.MarkaId IN (SELECT bf.Data FROM dbo.Split(@BrandFilter, ',') bf))
于 2013-07-16T06:24:45.417 回答
2

像这样:

SELECT * FROM
(
    SELECT
            ROW_NUMBER() OVER(ORDER BY  
            CASE WHEN @SortType = '1' THEN mt.Ad END ASC,
            CASE WHEN @SortType = '2' THEN mt.Ad END DESC,
            CASE WHEN @SortType = '3' THEN mt.Fiyat END ASC,
            CASE WHEN @SortType = '4' THEN mt.Fiyat END DESC) AS RowNr, * 
    FROM @MainTable mt
    WHERE mt.Fiyat > @MinPrice AND mt.Fiyat < @MaxPrice     
     AND (mt.MarkaId IN (SELECT bf.Data FROM dbo.Split(@BrandFilter, ',') bf) OR @BrandFilter = '')
) Result
WHERE RowNr > ((@PageNr-1) * 10) AND RowNr <= ((@PageNr) * 10)

在 your 的上部分支中if,缺少ANDWHERE子句的部分;在较低的分支中,检查是否是字符串的MarkaId一部分。当未指定时,@BrandFilterOR条件使相同的条件为真。@BrandFilter

于 2013-07-16T06:24:56.823 回答