473,761 Members | 9,480 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamic ORDER BY clause

2 New Member
Hi, I have a fairly simple select statement, but I want to do pagination and the sort order should be controlled by the user. The last part is causing me problems...

I use DB2 8.2.3 on Windows. My idea is to create a prepared statement (or a named query) instead of using dynamic SQL.

SELECT * FROM (SELECT ROWNUMBER() OVER(
ORDER BY CASE CAST(? AS SMALLINT)
WHEN 1 THEN a.firstname
WHEN 2 THEN a.lastname
WHEN 3 THEN a.workphone
WHEN 4 THEN a.title
ELSE a.lastname
END)
AS rownumber_,
a.contactid, a.firstname, a.lastname, a.workphone, a.title
FROM Contact a
WHERE a.contactId = ? AND a.deleted = 0
ORDER BY CASE CAST(? AS SMALLINT)
WHEN 1 THEN a.firstname
WHEN 2 THEN a.lastname
WHEN 3 THEN a.workphone
WHEN 4 THEN a.title
ELSE a.lastname
END
) as temp_ where rownumber_ between ? and ?

Is this really the right approach and how do I get to control the sort order (ascending/descending)?

What is the performance impact of using dynamic sql? I'm thinking it would be easier to maintain.

Best Regards,
Claus
Feb 20 '07 #1
1 6282
Snib
24 New Member
Dynamic SQL may be bad if you have a large amount of data on the table and start doing complicated predicate searches or repeated accesses in loops - you will have no idea what access path Db2 will pick until the dynamic SQL is run. You can attempt to predict it using EXPLAINs but if the RUNSTATS of the tabels you use fo the EXPLAIN change, which they will as the data on the tables grow, then the access paths for the dynamic SQL could change.

But, in the example code you only seem to have 4 order by types. It may be easier just to setup 4 static peices of SQL which return exactly the same columns but with different ORDER BY statements. The user can then select the order they want the data displayed in one the screen and your program just picks which peice of SQL to run.

Regards

Snib
Mar 17 '07 #2

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

Similar topics

7
3550
by: diroddi | last post by:
I am having a problem using a dynamic where clause. I have a feeling that I am overlooking something very simple, although I can't seem to figure it out. The error i'm getting is: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY full_name ASC LIMIT 0,25' Any help would be greatly appreciated.
7
2752
by: JJ_377 | last post by:
Can someone tell me why SQL seems to ignore my order by clause? I tried to run through the debugger, but the debugger stops at the select statement line and then returns the result set; so, I have no idea how it is evaluating the order by clause. THANK YOU! CREATE proc sprAllBooks @SortAscend varchar(4), @SortColumn varchar(10)
10
3011
by: Jozef de Veuster | last post by:
Hi, I'm trying to create a Stored Procedure that returns a recordset, but I want to be able to choose the ORDER BY clause in mijn parameter list of the Stored Procedure. Since CASE .. WHEN can only be used in the SELECT clause, I came up with the following: -- BEGIN SCRIPT -- DECLARE @blah AS VARCHAR(20) SET @blah = 'DOSSIER_CODE'
4
13069
by: Tim.D | last post by:
People, I've ventured into the wonderful world of Stored Procedures. My first experience has been relatively successful however I am stuck on using host variables to specifiy actualy table or column names in a FROM clause. After many hours or reading all manner of manuals I've discovered it appears this is not possible and that in order to so I need to further venture into dynamic SQL. My present procedure is based on all static SQL...
1
6114
by: mailar | last post by:
Hi, Can I use ORDER BY clause in my sql UDF that returns a table and has the folloing body. (trial_udf.sql) drop function aa@ create function aa() returns TABLE(empno varchar(20)) language SQL return select empno from employee order by empno@
26
17212
by: GreatAlterEgo | last post by:
Hi, This is my query which is embedded in a COBOL program. EXEC SQL SELECT DATE, AGE, DURATION, AMT INTO :LDATE, :L.AGE, :L.DURATION, :L.AMT FROM TAB1 WHERE CODE = :KEY.CODE AND SET = :KEY.SET AND DATE <= :KEY.DATE
13
17168
by: salad | last post by:
Operating in A97. I didn't receive much of a response conserning Pivot tables in Access. Pivot tables are nice, but a CrossTab will work for me too. Using a Pivot table, one is actually launching Excel for data viewing. I'd prefer the user stay in Access. Creating dynamic crosstab queries is pretty simple. The problem is that the column count may shrink or grow depending on the filter.
3
6041
by: Cindy | last post by:
I'm trying to use the NEWID function in dynamic SQL and get an error message Incorrect syntax near the keyword 'ORDER'. Looks like I can't do an insert with an Order by clause. Here's the code: SELECT @SQLString = N'INSERT INTO TMP_UR_Randoms(Admit_DOCID, Client_ID, SelectDate, SelectType,RecordChosen)' SELECT @SQLString = @SQLString + N'(SELECT TOP ' + @RequFilesST + ' Admit_DOCID, Client_ID, SelectDate, SelectType, RecordChosen...
1
3749
by: john | last post by:
I'm trying to build a LINQ expression that will use a dynamic construction of a LIKE statement in the WHERE clause, it would look something like this in SQL: WHERE TaskGroup Like "*00*" OR TaskGroup Like "*20*" It would be many variations on the above.
0
9531
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
9957
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
9905
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
9775
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8780
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
7332
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
6609
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();...
3
3456
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2752
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.