2009-10-25 104 views
1

WhenI調用這個存儲過程:SQL轉換失敗錯誤

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       

我得到錯誤:

Conversion failed when converting date and/or time from character string

這是我怎麼稱呼SP:

DECLARE @return_value int 

EXEC @return_value = [dbo].[GetSorted] 

     @OrderByColumn = 'AddedBy' 


SELECT 'Return Value' = @return_value 

GO 

UPDATE: 如果我使用多情況下的做法,如拳頭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 
+0

關於您的更新,要將訂單方向添加爲一個存儲過程的參數,您可以擴展CASE語句中的布爾表達式來檢查列和方向。請看我更新的答案。 – Tim 2009-10-25 15:52:36

回答

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 
+0

請參閱我的更新 – samuel 2009-10-25 15:26:40

+0

我更新了我的答案,將訂單方向作爲基於您的問題更新的參數。 – Tim 2009-10-25 15:47:03

3

您試圖轉換數據類型,並且datetime具有更高的優先級。基本上「AddedBy =‘鮑勃’」無法轉換......

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

其他不是必需的,對吧? – samuel 2009-10-25 14:58:28

+1

請參閱我的更新 – samuel 2009-10-25 15:27:10