Posts

Showing posts from July, 2008

Execute Dynamic SQL commands in SQL Server

In some applications having hard-coded SQL statements is not appealing, because of the dynamic nature of the queries being issued against the database server. Because of this sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can be done quite simply from the application perspective where the statement is built on the fly whether you are using ASP.NET , ColdFusion or any other programming language. But how do you do this from within a SQL Server stored procedure? SQL Server offers a few ways of running a dynamically built SQL statement. These ways are: Writing a query with parameters Using EXEC Using sp_executesql Writing a query with parameters This first approach is pretty straightforward if you only need to pass parameters into the WHERE clause of your SQL statement. Let’s say we need to find all records from the Customers table where City = ‘London’. This can be done easily as the following example shows.

Turning Tables into Delimited Text

Creating a Comma-Separated List of Authors for a Title in SQL Server In certain scenarios, representing data in a relational format might not be the most intuitive choice. For instance, when dealing with lists associated with rows, displaying them as comma-separated text can be more practical, especially for reports and online grids. In this blog post, I’ll share a scalar user-defined function (UDF) that implements this technique. The udf_Titles_AuthorList Function CREATE FUNCTION udf_Titles_AuthorList ( @title_id char ( 6 ) -- title ID from pubs database ) RETURNS varchar ( 255 ) -- List of authors -- No SCHEMABINDING reads data from another DB /* * Returns a comma-separated list of the last name of all * authors for a title. * * Example: * Select Title, dbo.udf_Titles_AuthorList(title_id) as [Authors] * FROM pubs..titles ORDER by Title ****************************************************************/ AS BEGIN DECLARE @lname varchar

How to rename a Stored Procedure in SQL

Sometimes by mistake, if you create a wrongly named stored procedure, you can easily rename the store procedure. Checkout following commands for renaming the stored procedure Syntax: sp_rename 'procedure_name1' , 'procedure_name2' procedure_name1 The current name of the stored procedure procedure_name2 The new name of the stored procedure. A stored procedure can be renamed. The new name should follow the rules for identifiers. Examples ` EXEC sp_rename 'spGetAvgGrade' , 'spNewAvgGrade' ; ` Output: Caution: Changing any part of an object name could break scripts and stored procedures. The object was renamed to ‘spNewAvgGrade’.` Explanation: In the above example, we change the name of the stored procedure spGetAvgGrade to spNewAvgGrade.

Implementing Custom Paging in ASP.NET with SQL Server 2005

Why Custom Paging? Custom paging allows you to get a limited number of records from a large database table that saves processing time of your database server as well as your application server and makes your application scalable, efficient and fast. In this article, I am going to explain how to create a stored procedure in SQL Server 2005 that allows you to pass startRowIndex and pageSize as a parameter and return you the number of records starting from that row index to the page size specified. It was possible in the SQL Server 2000 too but it was not as easy as in SQL Server 2005 is. -- EXEC LoadPagedArticles 10, 5 Let’s create the function CREATE PROCEDURE LoadPagedArticles -- Add the parameters for the stored procedure here @startRowIndex int , @pageSize int AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON ; -- increase the startRowIndex by 1 to avoid returning the last record ag

Execute Dynamic SQL commands in SQL Server

In some applications having hard coded SQL statements is not appealing, because of the dynamic nature of the queries being issued against the database server. Because of this sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can be done quite simply from the application perspective where the statement is built on the fly whether you are using ASP.NET , ColdFusion or any other programming language. But how do you do this from within a SQL Server stored procedure? SQL Server offers a few ways of running a dynamically built SQL statement. These ways are: Writing a query with parameters Using EXEC Using sp_executesql Writing a query with parameters This first approach is pretty straight forward if you only need to pass parameters into your WHERE clause of your SQL statement. Let’s say we need to find all records from the customers table where City = ‘London’. This can be done easily such as the following example s

Every SQL developer must know about sql case command

suppose We need a stored procedure that can be called by an application but the user wants to be able to sort by either first name or last name. One would be tempted to use dynamic SQL to solve this problem, but we can use CASE to create a dynamic SQL equivalent CREATE PROCEDURE dbo . getCustomerData @sortby VARCHAR ( 9 ) , @sortdirection CHAR ( 4 ) AS SET nocount ON SELECT customerid , firstname , lastname , statecode , statedescription , totalsales FROM dbo . Customer ORDER BY CASE @sortdirection WHEN 'asc' THEN CASE @sortby WHEN 'firstname' THEN firstname WHEN 'lastname' THEN lastname END END ASC , CASE @sortdirection WHEN 'desc' THEN CASE @sortby WHEN 'firstname' THEN firstname WHEN 'lastname' THEN lastname END END DESC GO How to execute EXEC dbo . getCustomerData 'lastname' , 'desc' A final requirement has crossed our desk

Convert Table To Pivot Table Using SQL Coalesce Operator

Using Coalesce to Pivot If you run the following statement against the AdventureWorks database, SELECT Name FROM HumanResources . Department WHERE ( GroupName = 'Executive General and Administration' ) you will come up with an expected result. You could run the following command if you want to pivot the data. DECLARE @DepartmentName VARCHAR ( 1000 ) SELECT @DepartmentName = COALESCE ( @DepartmentName , '' ) + Name + ',' FROM HumanResources . Department WHERE ( GroupName = 'Executive General and Administration' ) SELECT @DepartmentName AS DepartmentNames And get the result set with comma-separated in a single column.

SQL Server Function to Determine a Leap Year

The following scalar function takes in a year and returns a bit flag indicating whether the passing year is a leap year or not. create function dbo . fn_IsLeapYear ( @year int ) returns bit as begin return ( select case datepart ( mm , dateadd ( dd , 1 , cast ( ( cast ( @year as varchar ( 4 ) ) + '0228' ) as datetime ) ) ) when 2 then 1 else 0 end ) end go That’s all there is to it! The function takes in the year, appends ‘0228’ to it (for February 28th) and adds a day. If the month of the next day is a 2 (as extracted by the DATEPART function), then we’re still in February, so it must be a leap year! If not, it is not a leap year. Here are a few examples: select dbo . fn_IsLeapYear ( 1900 ) as 'IsLeapYear?' select dbo . fn_IsLeapYear ( 2000 ) as 'IsLeapYear?' select dbo . fn_IsLeapYear ( 2007 ) as 'IsLeapYear?' select dbo . fn_IsLeapYear ( 2008 ) as 'IsLeapYear?'