我想在不使用任何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)
谢谢..
答案 0 :(得分: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))
答案 1 :(得分: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)
在if
的上部分支中,AND
子句的WHERE
部分丢失;在下部分支中,检查MarkaId
是@BrandFilter
字符串的一部分。 <{1}}条件在未指定OR
时使相同的条件为真。