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