我在" Order By"中使用它时忽略了大小写SQL Server存储过程中的子句

时间:2015-12-08 13:30:59

标签: sql-server stored-procedures sql-order-by

萨拉姆,

我正在使用CASE END来指定要在ORDER BY子句中使用的列。 但问题是即使我将"Total"传递给过程,该过程也会忽略该子句,但是当我通过"ProductCode"时它会正常工作。

以下是出现此问题的部分:

ORDER BY     
            CASE    
                 WHEN @ORDER_BY1='ProductCode' THEN CAST( dbo.Items.ProductCode AS NVARCHAR)
                 --When I pass 'Total' in this procedure, it ignores it. So it won't be ordered by Total
                 WHEN @ORDER_BY1='Total' THEN CAST( COUNT(*) AS NVARCHAR)
            END ASC,
            CASE    
                 WHEN @ORDER_BY2='ProductCode' THEN CAST( dbo.Items.ProductCode AS NVARCHAR)
                 --When I pass 'Total' in this procedure, it ignores it. So it won't be ordered by Total
                 WHEN @ORDER_BY2='Total' THEN CAST( Count(*) AS NVARCHAR)
            END ASC

1 个答案:

答案 0 :(得分:0)

感谢Damien_The_Unbeliever

该条款未被忽略,但为了在COUNT(*)子句中使用ORDER BY,它必须是一个数值。并且因为每个CASE应该生成一个值类型,所以代码应该是这样的:

ORDER BY     

            CASE
                 WHEN @ORDER_BY1='Total' THEN CAST( COUNT(*) AS INT)
                 WHEN @ORDER_BY2='Total' THEN CAST( Count(*) AS INT)
            END ASC,

            CASE    
                 WHEN @ORDER_BY1='ProductCode' THEN CAST( dbo.Items.ProductCode AS NVARCHAR)
                 WHEN @ORDER_BY2='ProductCode' THEN CAST( dbo.Items.ProductCode AS NVARCHAR)
            END ASC