使用sp_executesql我想执行一个列的结果,该列在列上存储预先写好的查询,如下所示。
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
Dave.Gugg的结果回答
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
答案 0 :(得分:3)
您已关闭,只需用以下内容替换最后一个选择:
DECLARE @sql NVARCHAR(MAX)
SELECT @sql = ExtractSQL
FROM @StoredQueries
WHERE ID = @ID
EXEC sp_executesql @sql