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.

Select Middle Record

SELECT TOP 1 query in T-SQL helps to find the first or the last record of the table data sorted by some criteria. But what if we need to find exactly middle record entry in the table ? Below is a small T-SQL query snippet that demonstrates a technique how to get middle record in a single query

SELECT TOP 1 UserId
FROM (SELECT TOP 50 PERCENT UserId
FROM addressbook WITH (NOLOCK)
ORDER BY UserId ASC) AS T1
ORDER BY 1 DESC

Comments

- said…
Some people might advise you to do a top, reverse sort and then top.. but because of the two sorts this may not be very efficient on large datasets. I use something like the following;


With
allusers as (select ROW_NUMBER() OVER (ORDER BY UniqUser) as RowNumber ,* from users)
select * from allusers where RowNumber between 2 AND 4


You only need a single sort, and if you keep it to the way you were sorting your query to begin with, it should be optimized out.
MikeGledhill said…
This script didn't quite work for me in SQL Server 2008. I had to use this:


select * FROM
(
select ROW_NUMBER() OVER (ORDER BY UserID) as RowNumber , * FROM tblUsers
) tmp
where tmp.RowNumber between 2 AND 3

Popular posts from this blog

Check If Temporary Table Exists

Multiple NULL values in a Unique index in SQL

Row To Column