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.

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 again   SET @startRowIndex = @startRowIndex + 1 

 BEGIN

 SELECT  *  FROM  (

 Select  *,  

 ROW_NUMBER()  OVER  (ORDER  BY AutoID ASC)  as RowNum

 FROM Articles 

 )  as ArticleList

 WHERE RowNum BETWEEN @startRowIndex AND  (@startRowIndex + @pageSize)  - 1

 ORDER  BY AutoID ASC

 END

END

GO

Comments

Anonymous said…
I've used this same code and it works great, until you get into dealing with large datasets.
Anonymous said…
I'm curious how you figured out the initial page size?

Popular posts from this blog

Check If Temporary Table Exists

Multiple NULL values in a Unique index in SQL

Row To Column