Reputation: 3469
Using sp_executesql i would like to execute the results of a column that stores pre written queries on a column as show below.
DECLARE @ID AS INT =2
DECLARE @StoredQueries Table
(
ID INT IDENTITY(1,1),
ExtractSQL NVARCHAR(MAX)
)
INSERT INTO @StoredQueries
VALUES(
'SELECT [DepartmentID]
,[Name]
,[GroupName]
,[ModifiedDate]
FROM [AdventureWorks2008R2].[HumanResources].[Department]'
)
INSERT INTO @StoredQueries
VALUES(
'SELECT[ShiftID]
,[Name]
,[StartTime]
,[EndTime]
,[ModifiedDate]
FROM [AdventureWorks2008R2].[HumanResources].[Shift]
'
)
INSERT INTO @StoredQueries
VALUES(
'SELECT TOP 1000 [AddressID]
,[AddressLine1]
,[AddressLine2]
,[City]
,[StateProvinceID]
,[PostalCode]
,[SpatialLocation]
,[rowguid]
,[ModifiedDate]
FROM [AdventureWorks2008R2].[Person].[Address]'
)
SELECT * FROM @StoredQueries
WHERE ID =@ID
Results from Dave.Gugg answer
DECLARE @ID AS INT =2
DECLARE @StoredQueries Table
(
ID INT IDENTITY(1,1),
ExtractSQL NVARCHAR(MAX)
)
INSERT INTO @StoredQueries
VALUES(
'SELECT [DepartmentID]
,[Name]
,[GroupName]
,[ModifiedDate]
FROM [AdventureWorks2008R2].[HumanResources].[Department]'
)
INSERT INTO @StoredQueries
VALUES(
'SELECT[ShiftID]
,[Name]
,[StartTime]
,[EndTime]
,[ModifiedDate]
FROM [AdventureWorks2008R2].[HumanResources].[Shift]
'
)
INSERT INTO @StoredQueries
VALUES(
'SELECT TOP 1000 [AddressID]
,[AddressLine1]
,[AddressLine2]
,[City]
,[StateProvinceID]
,[PostalCode]
,[SpatialLocation]
,[rowguid]
,[ModifiedDate]
FROM [AdventureWorks2008R2].[Person].[Address]'
)
DECLARE @sql NVARCHAR(MAX)
SELECT @sql = ExtractSQL
FROM @StoredQueries
WHERE ID = @ID
EXEC sp_executesql @sql
Upvotes: 1
Views: 91
Reputation: 6771
You're close, just replace that very last select with this:
DECLARE @sql NVARCHAR(MAX)
SELECT @sql = ExtractSQL
FROM @StoredQueries
WHERE ID = @ID
EXEC sp_executesql @sql
Upvotes: 3