2010-06-14 66 views
0

我試圖選擇SQL中產品類別樹的層次結構。SQL中的條件公用表表達式(CTE)

我的代碼如下所示。我試圖實現動態排序順序,在SortOrder參數上使用IF或Case When。

如果@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 

回答

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 

的關鍵是讓所有排序的列(或表達式)的最後形成相同的數據類型。

+0

無法正常工作。 雖然,你的僞代碼不會做我想要實現的。 我希望@SortOrder可以像'createdate','salescount','name'或'custom'一樣更靜態。 每種情況都應該導致不同的SQL語句。 – MartinHN 2010-06-14 17:14:47

+0

我剛剛編輯了答案,現在我對您要查找的內容有了更清晰的瞭解。 – 2010-06-14 17:23:22

+0

哦,我應該按照從句的順序來做。 我改變了我的代碼,所有4列添加到數據集,這樣做是爲了通過: ORDER BY CASE \t WHEN @SortOrder = 'NameSortedOrder',那麼Categories.NameSortedOrder \t WHEN @SortOrder =「SalesCountOrder 'THEN Categories.SalesCountOrder \t WHEN @SortOrder ='DateCreatedOrder'THEN Categories.DateCreatedOrder \t ELSE Categories.SortOrder END – MartinHN 2010-06-14 18:35:39