473,748 Members | 8,779 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problems with case statement in where clause

8 New Member
I was wondering if someone would be able to tell me what is wrong with my code here:

SELECT COUNT(*)
FROM CALL
WHERE CALL.DESCRIPTIO N =
CASE
WHEN @Param1 = 'In' THEN 'In'
WHEN @Param1 = 'Out' THEN 'Out'
END

I am getting an error that parameter is correct.

And just in case there is any confusion, I am taking in 1 parameter that is either going to be 'In' or 'Out'. Depending on the param, I want to set Call.Descriptio n to either 'In' or 'Out'.

Thanks in advance!
Aug 6 '08
15 9393
ck9663
2,878 Recognized Expert Specialist
I believe the columns on the ORDER BY clause must be on your dataset or use ordinal position.

-- CK
Aug 13 '08 #11
ShadowTech
3 New Member
I'm testing this in SQL Server 2005, Management Studio.

Correct me if I'm wrong, but when you're just running a query in SS, you can just type the query, press 'Execute' and enter the parameters at that time, no? I'm confused because when I have a query with parameters in the SELECT or WHERE clause, it works perfectly fine.

Expand|Select|Wrap|Line Numbers
  1. SELECT     *
  2. FROM CALL
  3. WHERE CALL.DESCRIPTION =  @Param1
However, when I have the parameter in the ORDER BY, I'm being asked to define the variable. The exact error message: Msg 137, Level 15, State 2, Line 3
Must declare the scalar variable "@orderBy".

Expand|Select|Wrap|Line Numbers
  1. SELECT START_DATE, CALL_ID
  2. FROM CALL
  3. ORDER BY CASE WHEN @orderBy = 'A' THEN START_DATE, CALL_ID END
I guess the real question is this second bit of code correct? If so, what is causing the error message of 'Must declare the scalar variable 'OrderBy''? All the examples I've seen only show dynamic ORDER BY in stored procedures, so I don't know.

Thanks again.

Try declaring the variable
Expand|Select|Wrap|Line Numbers
  1. Declare @orderBy char(1)
  2. Set @orderBy = 'A'
  3. SELECT START_DATE, CALL_ID
  4. FROM CALL
  5. ORDER BY CASE WHEN @orderBy = 'A' THEN START_DATE, CALL_ID END
Aug 13 '08 #12
shlo
8 New Member
Try declaring the variable
Expand|Select|Wrap|Line Numbers
  1. Declare @orderBy char(1)
  2. Set @orderBy = 'A'
  3. SELECT START_DATE, CALL_ID
  4. FROM CALL
  5. ORDER BY CASE WHEN @orderBy = 'A' THEN START_DATE, CALL_ID END

So, I can't SET the variable. This will be a parameter passed in from my application and I won't know what the value will be beforehand (and even though I only included one case, there will be multiple cases in my actual query).

The DECLARE does get rid of the error message but does not give me the right results. I am also getting an error message when I try to include more than 1 value in the ORDER BY:

Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ','.
Aug 13 '08 #13
ck9663
2,878 Recognized Expert Specialist
What kind of application are you running that calls this query? It might be possible you build your query dynamically on your app side and run it accordingly.

-- CK
Aug 13 '08 #14
shlo
8 New Member
What kind of application are you running that calls this query? It might be possible you build your query dynamically on your app side and run it accordingly.

-- CK
No, it's not possible to build the query dynamically. It's a web application that uses BIRT (reporting tool).

Since I've found it really hard to construct and test queries in BIRT, I've been constructing/testing them in SS first. My current work around is to have 3 different reports that only differ in their ORDER BY... this works, but i thought it would be possible (and cleaner, easier to maintain) to combine the reports and have a parameter that dynamically determines ORDER BY.

At this point however, I am not even able to get a simple query to work in BIRT or SS, ie. the code below give me errors:

Expand|Select|Wrap|Line Numbers
  1. SELECT * 
  2. FROM CALL
  3. ORDER BY @orderBy
It seems weird that the above code doesn't work even though I use parameters galore in the SELECT and WHERE clause in all the other reports - makes me wonder if it's something particular to the ORDER BY?? Maybe this is just not possible? If that's the case, I will just keep my work around which isn't pretty but it works :(

Thanks for your help.
Aug 13 '08 #15
Delerna
1,134 Recognized Expert Top Contributor
Expand|Select|Wrap|Line Numbers
  1. SELECT * 
  2. FROM CALL
  3. ORDER BY @orderBy
  4.  
Order by works with field names. You can't use a variable in the order by like that

You can say
Expand|Select|Wrap|Line Numbers
  1. SELECT * 
  2. FROM CALL
  3. ORDER BY case when @orderBy='test' then FieldName1 else FieldName2 end
  4.  

Also from a previous post
Expand|Select|Wrap|Line Numbers
  1. Declare @orderBy char(1)
  2. Set @orderBy = 'A'
  3. SELECT START_DATE, CALL_ID
  4. FROM CALL
  5. ORDER BY CASE WHEN @orderBy = 'A' THEN START_DATE, CALL_ID END
  6.  
You can't reference multiple fields in the case like that
you need a case statement for each field
Expand|Select|Wrap|Line Numbers
  1. Declare @orderBy char(1)
  2. Set @orderBy = 'A'
  3. SELECT START_DATE, CALL_ID
  4. FROM CALL
  5. ORDER BY 
  6.    CASE WHEN @orderBy = 'A' THEN START_DATE ELSE CALL_ID END,
  7.    CASE WHEN @orderBy = 'A' THEN CALL_ID ELSE START_DATE END
  8.  
So if @orderBy='A' it will be ORDER BY START_DATE,CALL _ID
otherwise it will be ORDER BY CALL_ID,START_D ATE



At least, not in SQLServer 2000 you can't
Aug 14 '08 #16

Sign in to post your reply or Sign up for a free account.

Similar topics

4
5779
by: Russell | last post by:
I'm having a fit with a query for a range of dates. The dates are being returned from a view. The table/field that they are being selected from stores them as varchar and that same field also stores other fields from our dynamic forms. The field is called 'FormItemAnswer' and stores text, integer, date, float, etc. Anything the user can type into one of our web forms. The query looks like, select distinct from...
2
188940
by: Largo SQL Tools | last post by:
Can anyone tell me if it's possible to use a Case statement in a Where clause, and if so, the proper syntax? J.R. Largo SQL Tools The Finest Collection of SQL Tools Available http://www.largosqltools.com
1
7134
by: mirth | last post by:
I would like to update a decimal column in a temporary table based on a set of Glcodes from another table. I search for a set of codes and then want to sum the value for each row matching the Glcodes. The problem is I keep getting multiple rows returned errors. "Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. The statement has been...
4
28824
by: Chad Richardson | last post by:
I've always been mistified why you can't use a column alias in the group by clause (i.e. you have to re-iterate the entire expression in the group by clause after having already done it once in the select statement). I'm mostly a SQL hobbiest, so it's possible that I am not doing this in the most efficient manner. Anyone care to comment on this with relation to the following example (is there a way to acheive this without re-stating the...
4
1609
by: ree32 | last post by:
I know when you are using group by functions you have to include all the columns in the GROUP BY clause. But what I am having problems when using a case statement to determine whether to sum of not a column. eg. SELECT Country, Case WHEN Age<15 THEN Sum(Income) ELSE NULL END AS YouthIncome, Case WHEN Age>65 THEN Sum(Income) ELSE NULL END AS PensionIncome FROM WORLDTABLE
8
2480
by: Jeff Gilbert | last post by:
Hello all. I'd appreciate some help with this one: First the DDL: CREATE TABLE ( NOT NULL , NULL , NOT NULL , (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , NOT NULL CONSTRAINT DEFAULT
7
6266
by: mandible | last post by:
Hello I'm trying to have some control on how my data is ordered depending on an input parameter my question is in a stored procedure how can I do something like this at the end of my statement. pOrder as input value where pOrder can be 1 or 0
1
5012
by: priyanka2203 | last post by:
Hi guys, I have a doubt regarding the CASE statement. It might sound silly, but me being new to DB2, it is kind of a genuine doubt. Try helping me with this.. When we use a case statement (simple-case-statement-when-clause), in this - the value of the expression prior to the first WHEN keyword is tested for equality with the value of each expression that follows the WHEN keyword. Right? Then if the search condition is true, the THEN...
7
2991
by: pbd22 | last post by:
Hi. I really need some advice on fine-tuning a stored procedure that is the meat of the search logic on my site. Customers are allowed to save searches, which dumps the search logic in a table called SavedSearches for later access to the search. My problem started with the ORDERBY condition used for zipcode searches. The condition did something like: "order by CASE WHEN userID=67 THEN 1 WHEN userID=103 THEN 2 WHEN
5
15511
by: Sascha.Moellering | last post by:
Hi, I receive the error code SQL0338N if I try to compile this statement (part of the statement): .... left outer join lateral (SELECT * FROM LIZSYSABA.VWZL0359TBS WHERE tbs_name = CASE WHEN MC.type_txt = 'ZAB' THEN 'BII' ELSE 'STD' END) AS TB1 on CASE WHEN MC.fixed_date_dat IS NULL THEN cast('01.01.2007' as date) + MC.rel_shift_NR DAY ELSE MC.fixed_date_dat END
0
8989
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8828
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9367
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9319
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8241
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6795
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2213
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.