Dynamic/Conditional Order By Clause in SQL Server/T-SQL
25 January 2009 - 5:42 PM / by Dominic Pettifer. 6 Comments
Technical Article - This article shows you how to achieve a conditional Order By clause in your SQL Server Stored Procedures, without having to resort to inline SQL in your applications, or Dynamic SQL (yuck!) in your Stored Procedures.
Inline SQL or Stored Procedures
You've probably come across times when you needed to sort a recordset dynamically in a Stored Procedure based on an input parameter. For instance, if you're displaying records on a webpage with sortable columns, like on most ecommerce sites. You could use an inline SQL statement dynamically built in your ASP/PHP server-side code with string concatenation eg:
string sql = "SELECT * FROM Products ORDER BY ";
if(Request.QueryString["orderBy"] == "NameAsc")
{
sql += "Name ASC";
}
else if(Request.QueryString["orderBy"] == "NameDesc")
{
sql += "Name DESC";
}
else if(......etc etc
However, you're probably using a Stored Procedure for reasons such as performance (execution plan is cached in a Sproc), maintainability (string concatenation can get messy with complex queries), prevent security vulnerabilities (such as SQL Injection), and maybe you want to achieve efficient database tier paging using SQL Server 2005's ROW_NUMBER() function.
Introducing the CASE Function
The trick is to use the CASE function, but there are quirks with this that can trip you up. First of all you declare a Stored Procedure with an Order By input parameter and apply the CASE to the Order By clause like this:
CREATE PROCEDURE GetProducts
(
@OrderBy VARCHAR(50),
@Input2 VARCHAR(30)
)
AS
BEGIN
SET NOCOUNT ON
SELECT Id, ProductName, Description, Price, Quantity
FROM Products
WHERE ProductName LIKE @Input2
ORDER BY
CASE
WHEN @OrderBy = 'ProductNameAsc' THEN ProductName
END ASC,
CASE
WHEN @OrderBy = 'ProductNameDesc' THEN ProductName
END DESC
END
Ascending and Descending actions need to be grouped into separate CASE statements, separated with a comma. In your server-side code/script make sure to append 'Asc' or 'Desc' onto the order by string, or you could have two Stored procedure input parameters for column name and order by direction if you want.
Multiple Columns with Different DataTypes
You'll hit problems when you try to include multiple columns with different data types (VARCHAR, INT etc.). Eg:
ORDER BY
CASE
WHEN @OrderBy = 'ProductNameAsc' THEN ProductName
WHEN @OrderBy = 'QuantityAsc' THEN Quantity
END ASC
...will throw an error because ProductName is a VARCHAR and Quantity is an INT...
Conversion failed when converting the nvarchar value 'Value' to data type int.
Warning: Null value is eliminated by an aggregate or other SET operation.
I've seen people wrap the column around a convert function eg.
WHEN @OrderBy = 'QuantityAsc' THEN CONVERT(VARCHAR(32), Quantity)
DON’T do this as the order by will be different as a string versus it's original data type (eg. 30 will come before 4 as the first character 3 is earlier in the alphebet then 4). This is especially true with DATETIME types as the CONVERT function could convert to into any number of date time formats (2009/01/15, 01/15/2009 etc.)
Instead you have to separate each datatype into separate groups of case statements like this:
SELECT Id, ProductName, Description, Price, Quantity
FROM Products
WHERE ProductName LIKE @Input2
ORDER BY
CASE –- VARCHAR types ascending
WHEN @OrderBy = 'ProductNameAsc' THEN ProductName
END ASC,
CASE –- VARCHAR types descending
WHEN @OrderBy = 'ProductNameDesc' THEN ProductName
END DESC,
CASE -- INT types ascending
WHEN @OrderBy = 'QuantityAsc' THEN Quantity
END ASC,
CASE -- INT types descending
WHEN @OrderBy = 'QuantityDesc' THEN Quantity
END DESC,
CASE -- MONEY types ascending
WHEN @OrderBy = 'PriceAsc' THEN Price
END ASC,
CASE -- MONEY types descending
WHEN @OrderBy = 'PriceDesc' THEN Price
END DESC,
CASE -- Default order by
WHEN 1 = 1 THEN ProductName
END ASC
Remember to provide a default Order By for when none of the CASE statements match.
Paging With ROW_NUMBER()
You can also use this technique with database tier paging using the ROW_NUMBER() function in SQL Server 2005/2008:
SELECT
Id,
ProductName,
Deacription,
Quantity
FROM
(
SELECT ROW_NUMBER() OVER(
ORDER BY
CASE
WHEN @OrderBy = 'ProductNameAsc' THEN ProductName
END ASC,
CASE
WHEN @OrderBy = 'ProductNameDesc' THEN ProductName
END DESC,
CASE
WHEN 1 = 1 THEN ProductName
END ASC,
//-- Snip --//
) AS RowNumber,
Id,
ProductName,
Description,
Price,
Quantity
FROM Products
WHERE ProductName LIKE @Input2
) i
WHERE RowNmber BETWEEN @FirstRecord AND @LastRecord
ORDER BY RowNumber ASC
Friday, June 24, 2011
Thursday, June 9, 2011
SSRS Report Series with Null value
yes,it was one the bad days when you get stuck with unknown devil (so called bug where you don't have any idea whats happening)..
in SSRS dundas chart,today I was publishing a chart where a series (months of year) has value in some places but not in all.but series was visible for all the x - axis data ...after juggling alot I found a solution..you can see the solution here
http://support2.dundas.com/OnlineDocumentation/WebChart2005/Data_Empty_Data.html
In short ..series have a property of empty points ..just make changes over there
in SSRS dundas chart,today I was publishing a chart where a series (months of year) has value in some places but not in all.but series was visible for all the x - axis data ...after juggling alot I found a solution..you can see the solution here
http://support2.dundas.com/OnlineDocumentation/WebChart2005/Data_Empty_Data.html
In short ..series have a property of empty points ..just make changes over there
Thursday, June 11, 2009
Performence Issues :Get Worst Performing T-SQL statement
While doing some performence issues in SQL 2005 I came across with this particular Artical ..
http://www.databasejournal.com/features/mssql/article.php/3802936/Finding-the-Worst-Performing-T-SQL-Statements-on-an-Instance.htm
this really helps if u want to know what all the T-SQL statement are worst performer
...............
Enjoy reading
http://www.databasejournal.com/features/mssql/article.php/3802936/Finding-the-Worst-Performing-T-SQL-Statements-on-an-Instance.htm
this really helps if u want to know what all the T-SQL statement are worst performer
...............
Enjoy reading
Thursday, March 26, 2009
Normalization In SQL
What is Normalization?Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process: eliminating redundant data (for example, storing the same data in more than one table) and ensuring data dependencies make sense (only storing related data in a table). Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored. The Normal FormsThe database community has developed a series of guidelines for ensuring that databases are normalized. These are referred to as normal forms and are numbered from one (the lowest form of normalization, referred to as first normal form or 1NF) through five (fifth normal form or 5NF). In practical applications, you'll often see 1NF, 2NF, and 3NF along with the occasional 4NF. Fifth normal form is very rarely seen and won't be discussed in this article.
Before we begin our discussion of the normal forms, it's important to point out that they are guidelines and guidelines only. Occasionally, it becomes necessary to stray from them to meet practical business requirements. However, when variations take place, it's extremely important to evaluate any possible ramifications they could have on your system and account for possible inconsistencies. That said, let's explore the normal forms. First Normal Form (1NF)First normal form (1NF) sets the very basic rules for an organized database: Eliminate duplicative columns from the same table. Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key). Second Normal Form (2NF)Second normal form (2NF) further addresses the concept of removing duplicative data: Meet all the requirements of the first normal form. Remove subsets of data that apply to multiple rows of a table and place them in separate tables. Create relationships between these new tables and their predecessors through the use of foreign keys. Third Normal Form (3NF)Third normal form (3NF) goes one large step further: Meet all the requirements of the second normal form. Remove columns that are not dependent upon the primary key. Fourth Normal Form (4NF)Finally, fourth normal form (4NF) has one additional requirement: Meet all the requirements of the third normal form. A relation is in 4NF if it has no multi-valued dependencies.
Before we begin our discussion of the normal forms, it's important to point out that they are guidelines and guidelines only. Occasionally, it becomes necessary to stray from them to meet practical business requirements. However, when variations take place, it's extremely important to evaluate any possible ramifications they could have on your system and account for possible inconsistencies. That said, let's explore the normal forms. First Normal Form (1NF)First normal form (1NF) sets the very basic rules for an organized database: Eliminate duplicative columns from the same table. Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key). Second Normal Form (2NF)Second normal form (2NF) further addresses the concept of removing duplicative data: Meet all the requirements of the first normal form. Remove subsets of data that apply to multiple rows of a table and place them in separate tables. Create relationships between these new tables and their predecessors through the use of foreign keys. Third Normal Form (3NF)Third normal form (3NF) goes one large step further: Meet all the requirements of the second normal form. Remove columns that are not dependent upon the primary key. Fourth Normal Form (4NF)Finally, fourth normal form (4NF) has one additional requirement: Meet all the requirements of the third normal form. A relation is in 4NF if it has no multi-valued dependencies.
Saturday, March 21, 2009
System Sp's Used in SQL server
SP's are Precompiled T-SQL statement that are stored on the server .SQL server supplies a group pf SP's collectively called system SP.By using these SP's we can easily and quickly access,update, andmaintain inforamtion that is stored in sytem tables.These stored Procedure Start with sp_
Few of them are as fallows, these can be very useful for getting information while working with SQL server.
1)sp_help:This sp is used to get information about a DBobject which is any object listed in sysobject table or user defined datatype
i)sp_help give information about the object of current DB
ii)in case no parameter it gives information about all the objects in current DB.
syntax: sp_help objname
2)sp_helpDB:This gives information about a specified DB or all theDB's Present in the server
syntax: sp_helpdb objname
in case no parameter it gives information about all the DB's
3)sp_helpSql:very useful sp while working on sql ,it give u help on some topic in otherwords it can give you T-sql statement of some topic e.g. datatype,expression or text function
i) you must include quotation marks around topic parameter
ii)you can enter just few letters of a particular topic to identify it then help on the specified topic is displayed.
syntax: sp_helpsql 'create tablename'
4)sp_who:This reports information about a specific use,a specified SQL server process,all currently running process or all active process
This can be very useful while troubleshooting sql server or when u are facing performence issues with server.
syntax: sp_who
Few of them are as fallows, these can be very useful for getting information while working with SQL server.
1)sp_help:This sp is used to get information about a DBobject which is any object listed in sysobject table or user defined datatype
i)sp_help give information about the object of current DB
ii)in case no parameter it gives information about all the objects in current DB.
syntax: sp_help objname
2)sp_helpDB:This gives information about a specified DB or all theDB's Present in the server
syntax: sp_helpdb objname
in case no parameter it gives information about all the DB's
3)sp_helpSql:very useful sp while working on sql ,it give u help on some topic in otherwords it can give you T-sql statement of some topic e.g. datatype,expression or text function
i) you must include quotation marks around topic parameter
ii)you can enter just few letters of a particular topic to identify it then help on the specified topic is displayed.
syntax: sp_helpsql 'create tablename'
4)sp_who:This reports information about a specific use,a specified SQL server process,all currently running process or all active process
This can be very useful while troubleshooting sql server or when u are facing performence issues with server.
syntax: sp_who
Thursday, March 19, 2009
Fetching Top n data from SQL Server table
Here is the way::
Select top n columnname from tblname
if you have 2 data same the use With tie
Select top n with tie colname from tblname
order by colname
Note : OrderBy is required for with tie
Select top n columnname from tblname
if you have 2 data same the use With tie
Select top n with tie colname from tblname
order by colname
Note : OrderBy is required for with tie
Subscribe to:
Posts (Atom)
