Is it possible to execute a SQL statement Stored in a Table, with T-SQL?
DECLARE @Query text SET @Query = (Select Query FROM SCM.dbo.CustomQuery)
The statements that are stored in the table are ad-hoc statements which could be SELECT TOP 100 * FROM ATable to more complex statements:
Select J.JobName As Job, JD.JobDetailJobStart AS StartDate, JD.JobDetailJobEnd AS EndDate, ( SELECT (DATEDIFF(dd, JD.JobDetailJobStart, JD.JobDetailJobEnd) + 1) -(DATEDIFF(wk, JD.JobDetailJobStart, JD.JobDetailJobEnd) * 2) -(CASE WHEN DATENAME(dw, JD.JobDetailJobStart) = 'Sunday' THEN -1 ELSE 0 END) -(CASE WHEN DATENAME(dw, JD.JobDetailJobEnd) = 'Saturday' THEN -1 ELSE 0 END) ) AS NumberOfWorkingDays, JD.JobDetailDailyTarget AS DailyTarget, JD.JobDetailWeeklyTarget AS WeeklyTarget, JD.JobDetailRequiredQTY AS RequiredQuantity, ( Select SUM(sJL.JobLabourQuantityEmployees) From JobLabour sJL ) AS NumberOfEmployees, ( Select SUM((sEM.EmployeeDesignationDefaultRate * sJL.JobLabourQuantityEmployees)*8)*(SELECT (DATEDIFF(dd, JD.JobDetailJobStart, JD.JobDetailJobEnd) + 1) -(DATEDIFF(wk, JD.JobDetailJobStart, JD.JobDetailJobEnd) * 2) -(CASE WHEN DATENAME(dw, JD.JobDetailJobStart) = 'Sunday' THEN -1 ELSE 0 END) -(CASE WHEN DATENAME(dw, JD.JobDetailJobEnd) = 'Saturday' THEN -1 ELSE 0 END)) from EmployeeDesignation sEM Inner join JobLabour sJL on sJL.EmployeeDesignationID = sEM.EmployeeDesignationID ) AS FullEmployeeRate from Job J Inner Join JobDetail JD on JD.JobID = J.JobID Inner Join JobLabour JL on JL.JobID = J.JobID WHERE J.JobActive = 0
I want to execute the @Query Variable that I declared from T-SQL. Is this possible? (I am running a MSSQL 2005 enviroment)
Advertisement
Answer
You can use
EXECUTE sp_executesql @Query
to run your T-SQL
Here’s a link to the MS docn for SQL Server 2005
http://msdn.microsoft.com/en-us/library/ms188001%28v=sql.90%29.aspx