If the datatype of the @sortBy
stored procedure parameter or local variable is anything smaller than the length of "Description", i.e. varchar(11), then that is your problem. For example, if @sortBy
is varchar(10), then "Description" becomes "Descriptio" (first 10 chars) and "BackupJobType" becomes "BackupJobT", but the other column names fit. If this is the case, change the @sortBy
data type of the procedure parameter and/or local variable to varchar(128).
CASE not working properly in SQL Server stored procedure
-
05-06-2023 - |
Question
I'm having an issue with using the CASE
statement to change my ORDER BY
statement in a stored procedure.
I'm sending in a parameter, @sortBy
, which contains the name of the column to order by.
My issue is that the CASE
statement works for most of the columns, but not others:
SELECT * FROM TapeView
ORDER BY
CASE
WHEN @sortBy = 'BackupJobType' THEN [BackupJobType]
WHEN @sortBy = 'ItemID' THEN [ItemID]
WHEN @sortBy = 'MediaType' THEN [MediaType]
WHEN @sortBy = 'Category' THEN [Category]
WHEN @sortBy = 'Description' THEN [Description]
WHEN @sortBy = 'PlantName' THEN [PlantName]
WHEN @sortBy = 'BackupType' THEN [BackupType]
WHEN @sortBy = 'UserID' THEN [UserID]
END
For some reason, this works fine for every column except for BackupJobType
and Description
.
I have checked the value of the parameter being sent in and the names of the columns, and am 100% certain that they are correct.
I have a nearly-identical query on another page and both of these columns are working fine there.
Any ideas?
Edit: I forgot to mention that all of these columns are varchar datatypes
Solution
OTHER TIPS
The problem is probably caused by types. I would expect the id
s to be a problem too, if they are numeric.
Putting each condition in a separate clause should fix the problem:
ORDER BY (CASE WHEN @sortBy = 'BackupJobType' THEN [BackupJobType] END),
(CASE WHEN @sortBy = 'ItemID' THEN [ItemID] END),
(CASE WHEN @sortBy = 'MediaType' THEN [MediaType] END),
(CASE WHEN @sortBy = 'Category' THEN [Category] END),
(CASE WHEN @sortBy = 'Description' THEN [Description] END),
(CASE WHEN @sortBy = 'PlantName' THEN [PlantName] END),
(CASE WHEN @sortBy = 'BackupType' THEN [BackupType] END),
(CASE WHEN @sortBy = 'UserID' THEN [UserID] END)
The clauses that don't match will all product NULL
s, so they will not affect the ordering.