SQL中的条件公用表表达式(CTE)

时间:2010-06-14 16:31:05

标签: sql-server common-table-expression

我正在尝试在SQL中选择产品类别树的层次结构。

我的代码如下所示。我正在尝试使用IF或Case在SortOrder参数上实现动态排序顺序。

如果@SortOrder等于'sortorder',则注释行应该是活动的。我试图在它周围添加If Else声明,但我失败了......

你能帮忙吗?

CREATE PROCEDURE [dbo].[ProductCategory_SelectHierarchy]
    @SortOrder varchar(30)
AS
    SET NOCOUNT ON;

WITH Categories (Id,ParentId,SortOrder,RowOrder) as
(
        SELECT  parentCategory.Id,
                        parentCategory.ParentId,
                        parentCategory.SortOrder,
                        --cast(REPLACE(STR(parentCategory.SortOrder, 8), ' ', '0') as varchar(30)) 'RowOrder'
                        cast(CAST(DATEPART(YEAR, parentCategory.DateCreated) as varchar(4)) + 
                        CAST(DATEPART(MONTH, parentCategory.DateCreated) as varchar(2)) + 
                        CAST(DATEPART(DD, parentCategory.DateCreated) as varchar(2)) + 
                        CAST(DATEPART(HOUR, parentCategory.DateCreated) as varchar(2)) as varchar(50)) 'RowOrder'
        FROM        ProductCategories parentCategory
        WHERE       ParentId = 0

        UNION ALL

        SELECT  childCategories.Id,
                        childCategories.ParentId,
                        childCategories.SortOrder,
                        --cast(Categories.RowOrder + REPLACE(STR(childCategories.SortOrder, 8), ' ', '0') as varchar(30)) 'RowOrder'
                        cast(Categories.RowOrder + '/' + CAST(DATEPART(YEAR, childCategories.DateCreated) as varchar(4)) + 
                        CAST(DATEPART(MONTH, childCategories.DateCreated) as varchar(2)) + 
                        CAST(DATEPART(DD, childCategories.DateCreated) as varchar(2)) + 
                        CAST(DATEPART(HOUR, childCategories.DateCreated) as varchar(2)) as varchar(50)) 'RowOrder'
        FROM        ProductCategories childCategories
        JOIN        Categories
        ON          childCategories.ParentId = Categories.Id
)

SELECT pc.*, Categories.RowOrder 
FROM Categories 
INNER JOIN ProductCategories pc ON pc.Id = Categories.Id
ORDER BY RowOrder

1 个答案:

答案 0 :(得分:0)

你应该可以这样排序:

ORDER BY
    CASE
        WHEN @SortOrder = 'date_column' THEN CONVERT(VARCHAR(20), date_column, 120)
        WHEN @SortOrder = 'customer_id' THEN RIGHT(REPLICATE('0', 20) + CAST(customer_id AS VARCHAR(20)), 20)
        WHEN @SortOrder = 'name' THEN name
        ELSE sort_order
    END

关键是让所有可排序列(或表达式)最终成为相同的数据类型。