Thursday, February 9, 2012

Actually, its a T-SQL question

I am trying to update a project using plaintext sql commands to stored procedures. I am currently working on

orderby = request.querystring("orderby")
if orderby = "" then orderby = "name"
sql="select * from products order by " & orderby"
rs.open sql,conn,3,3

(yes, that's classic ASP but its the t-sql that's a problem, not the aspWink [;)])
orderby can be "name","code","qty","price"
The stored procedure I have is

CREATE PROCEDURE DBO.GetSortedProducts_sp
@.sort int
AS</P><P> SELECT
*
FROM
PRODUCTS
ORDER BY
case
when @.sort=1 then name --varchar(100)
when @.sort=2 then code --varchar(20)
when @.sort=3 then qty --int
when @.sort=4 then price --decimal 9(19,4)
end
GO

Only @.sort=3 and @.sort=4 work. For @.sort=1 and @.sort=2, I get the following error:
Server: Msg 8114, Level 16, State 5, Procedure GetSortedProducts_sp, Line 5
Error converting data type varchar to numeric.
I have included the column types in the stored procedure above for reference.
If I write out the stored procedure in Query Analyzer I get the following error:
Syntax error converting the varchar value 'Prod-1' to a column of data type int.
Note that if I use "select * from products order by code" then it works fine. Any help please?

Confused [8-)]|||My guess is when you are using CASE the columns should all be of same datatype.|||As Dinakar said, with the CASE construct you've used all options must result in the same datatype.
Try this approach instead:
SELECT
*
FROM
PRODUCTS
ORDER BY
case when @.sort=1 then name end,
case when @.sort=2 then code end,
case when @.sort=3 then qty end,
case when @.sort=4 then price end

|||interesting...thx

No comments:

Post a Comment