30 pts.
 SQL Server 2005: SQL statement in a variable
Can anybody help me? "HOW TO ASSIGN A SQL-STATEMENT IN A VARIABLE". FOR EXAMPLE : TO ASSIGN A STRING IN A VARIABLE, WE DO LIKE THIS: DECLARE @A AS VARCHAR(20) SET @A='HAI' PRINT @A OUTPUT: HAI SIMILARLY HOW TO ASSIGN A SQL-STATEMENT IN A VARIABLE.

Software/Hardware used:
ASKED: May 8, 2009  6:37 AM
UPDATED: June 19, 2013  6:33 PM

Answer Wiki:
This is the quick and dirty: DECLARE @SQL VARCHAR(8000) , @SQLVariable INT SET @SQLVariable = 1 SET @SQL = 'SELECT * FROM Table WHERE Value = ' + CAST( @SQLVariable AS VARCHAR( 5 ) ) EXEC( @SQL ) For a more secure solution research sp_executesql in BOL.
Last Wiki Answer Submitted:  June 19, 2013  6:33 pm  by  Michael Tidmarsh   14,060 pts.
All Answer Wiki Contributors:  Michael Tidmarsh   14,060 pts. , Koverton44   150 pts.
To see all answers submitted to the Answer Wiki: View Answer History.


Discuss This Question:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _


 

You might want to share whith us the reasons why you want to store the statement in a variable. What are you planning to do ?

You could store the statement as a string, and then execute it as dynamic sql.

 63,580 pts.

 

Sir,

In my code i am using a lot of sql statements which are repeated no. of times, so i thought why to repeat so
many times instead of that i can assign the the sql statements in one one variable & use that varible wherever i need it, it makes my job is easy. Hope u got me.

Narendar.

 30 pts.

 

You could put your SQL statements in a stored procedure. That would be better that using dynamic SQL for security reasons.

 63,580 pts.

 

You could put your SQL statements in a stored procedure. That would be better that using dynamic SQL for security reasons.

I am using sql statements in a stored procedure.

 30 pts.

 

You could put your repeating SQL statements in another procedure, so you can call it instead of writing the statements again every time you need them.

 63,580 pts.