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.

Find 3rd max salary

Count() will give the numer of non-null values in sxp.

Select salary from sal s
Where 2=(select count(8) from sal s1 where s.salary
The same co-related query cabn be used to find the nth max salary the number with the where clause should be n-1 for .

Comments

Davinder Singh said…
I didn't get this query yet. plz justify with example.
Davinder Singh said…
The correct syntax is listed below:
SELECT name,sal FROM emp e1 Where n=(select Count(distinct(sal)) From emp e2
WHERE e2.sal>=e1.sal)

Here n stands for nth highest salary. CHEERS.
satya said…
This comment has been removed by the author.
satya said…
select top 1 sal from (select distinct top 3 sal from table order by sal desc ) a
order by sal

Popular posts from this blog

Check If Temporary Table Exists

Multiple NULL values in a Unique index in SQL

Row To Column