Unlimited Web Space

Enjoy Unlimited web hosting

Nov 7, 2011

How to declare a SQL query and execute it in SQL Server

Sometimes consequences arise in which you need to declare a query and execute it a number of times when you are working in SQL Server or any Server in SQL. There are store procedures that requires a query to be declared and execute it under some loop or even in an if else statement.


One way is to write the query everytime, but when we have multiple values in the query, say the query needs to change some of it's features everytime you call, it is necessary to declare a query as a variable and execute it whenever needed. We have the query as below:

declare @query nvarchar(max)
set @query = ('select * from Table')
exec (@query)

The above shows a very simple SQL Server query to select a table. From the above example, we can bend it to the way we like. When we learned, 1 + 1 = 2, We don't always need to explain what will be 2 + 2. :)

Just for a heads up, I would like to add one more example:

declare @Cnt int set @Cnt=10
declare @query nvarchar(max)
set @query = ('select * from Table' where Column_ID = @Cnt)
exec (@query)
set @Cnt = @Cnt + 1
exec (@Query)

and so on.
NB: Do not forget the brackets that hold @query. SQL Server will not execute the query without the brackets

No comments:

Post a Comment