sql - ORDER BY depending on parameter results in error -


i have stored procedure initiates order depending on parameter:

drop procedure [dbo].[getusersbyclusterandusername]   go create procedure [dbo].[getusersbyclusterandusername]     @sortfield [nvarchar] (256) = 'username',     @sortorder [int] = 0     select * [user]      order     case when @sortorder = 0         case              when @sortfield = 'username' user_username              when @sortfield = 'lastlogindate' user_lastlogindate              when @sortfield = 'creationdate' user_creationdate end     end asc,         case when @sortorder = 1         case             when @sortfield = 'username' user_username              when @sortfield = 'lastlogindate' user_lastlogindate             when @sortfield = 'creationdate' [user_creationdate] end     end desc return 0 go 

however... if call procedure this:

exec dbo.getusersbyclusterandusername @sortorder=1, @sortfield='username' 

i following error:

msg 241, level 16, state 1, procedure getusersbyclusterandusername, line 7 conversion failed when converting date and/or time character string. 

why try convert date/time. can please help?

the problem type conversion case. when using order by in way, use multiple case statements:

order (case when @sortorder = 0 , @sortfield = 'username' user_username end),          (case when @sortorder = 0 , @sortfield = 'user_lastlogindate' user_lastlogindate end),          (case when @sortorder = 0 , @sortfield = 'user_creationdate' user_creationdate end),          (case when @sortorder = 1 , @sortfield = 'username' user_username end) desc,          (case when @sortorder = 1 , @sortfield = 'user_lastlogindate' user_lastlogindate end) desc,          (case when @sortorder = 1 , @sortfield = 'user_creationdate' user_creationdate end) desc 

the problem case has single output type, determined when query compiled. type based on logic combining types form then clause. so, result each then clause converted overall type -- , error occurs.

you can read data precedence rules here. solution simple: use multiple case statements.


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -