SQL转换失败错误

时间:2009-10-25 14:09:16

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

当我调用此存储过程时:

ALTER PROCEDURE [dbo].[GetSorted]   
(
   @OrderByColumn   nvarchar(256)

)
AS
SET NOCOUNT ON      

   SELECT itDocs.AddedDate, itDocs.AddedBy  FROM itDocs      
    ORDER BY 
             CASE WHEN @OrderByColumn='AddedDate' THEN itDocs.AddedDate
                  WHEN @OrderByColumn='AddedBy' THEN itDocs.AddedBy 

        END  ASC                        

我收到错误:

  

转换日期时转换失败   和/或来自字符串的时间

这就是我称之为SP的方式:

DECLARE @return_value int

EXEC    @return_value = [dbo].[GetSorted]

        @OrderByColumn = 'AddedBy'


SELECT  'Return Value' = @return_value

GO

更新 如果我按照第2个答案的建议使用多案例方法, 尝试添加另一个方向时,我收到错误:

  ORDER BY  
        CASE WHEN @OrderDirection=0 THEN            
           CASE WHEN @OrderByColumn='AddedDate' THEN itDocs.AddedDate END ASC,
           CASE WHEN @OrderByColumn='AddedBy' THEN   itDocs.AddedBy END ASC    
        end       
       CASE WHEN @OrderDirection=1 THEN  

2 个答案:

答案 0 :(得分:3)

您正在尝试转换数据类型,而datetime具有更高的优先级。基本上“添加By ='bob'”无法转换......

SELECT
    itDocs.AddedDate, itDocs.AddedBy
FROM
    itDocs      
ORDER BY
    CASE OrderByColumn WHEN 'AddedDate' THEN itDocs.AddedDate ELSE '19000101' END,
    CASE OrderByColumn WHEN 'AddedBy' THEN itDocs.AddedBy ELSE '' END

答案 1 :(得分:2)

这是一篇很好的文章,解释了您收到的错误:

Using CASE in ORDER BY clause

您可以将存储过程更改为以下内容,以允许ORDER BY子句中的CASE工作(现在已编辑为包含订单方向作为参数):

ALTER PROCEDURE [dbo].[GetSorted]   
(
    @OrderByColumn   nvarchar(256),
    @OrderDirection  int
)
AS
SET NOCOUNT ON             
   SELECT itDocs.AddedDate, itDocs.AddedBy FROM itDocs          
      ORDER BY              
         CASE WHEN @OrderByColumn='AddedDate' AND @OrderDirection=0 THEN itDocs.AddedDate END ASC,
         CASE WHEN @OrderByColumn='AddedBy' AND @OrderDirection=0 THEN itDocs.AddedBy END ASC,         
         CASE WHEN @OrderByColumn='AddedDate' AND @OrderDirection=1 THEN itDocs.AddedDate END DESC,
         CASE WHEN @OrderByColumn='AddedBy' AND @OrderDirection=1 THEN itDocs.AddedBy END DESC