如何将exec的结果赋给变量

时间:2016-06-07 10:18:57

标签: sql-server exec varchar

如何将exec命令的结果分配给变量。如下所示,所以当我选择@sql2时,我得到执行的varchar sql的结果。

declare @sql varchar(500)
declare @sql2 varchar(max)
set @sql = 'SELECT 
                PDB.OutletBrandID, OB.BrandName
            FROM 
                ProductDistributionBrand PDB
            INNER JOIN 
                [IND_roadchef].dbo.OutletBrands OB 
            ON 
                PDB.OutletBrandID = OB.OutletBrandID

            FOR XML PATH(''ProductDistributionBrandDetail''),ROOT(''ProductDistributionBrandDetails''),TYPE'    
--select @sql
set @sql2 = exec(@sql)  
select @sql2            

3 个答案:

答案 0 :(得分:2)

使用输出参数:

declare @sql nvarchar(500)
declare @xml XML

set @sql = 'set @xml = (SELECT ..... FOR XML PATH(''ProductDistributionBrandDetail''),ROOT(''ProductDistributionBrandDetails''),TYPE)'    

EXEC sp_executesql @sql, N'@xml XML output', @xml = @xml OUTPUT

select @xml

答案 1 :(得分:0)

您可以使用表变量。试试这样,

DECLARE @sql TABLE (col1 VARCHAR(500))
DECLARE @sql2 VARCHAR(max)

SET @sql2 = 'SELECT 
                PDB.OutletBrandID, OB.BrandName
            FROM 
                ProductDistributionBrand PDB
            INNER JOIN 
                [IND_roadchef].dbo.OutletBrands OB 
            ON 
                PDB.OutletBrandID = OB.OutletBrandID

            FOR XML PATH(''ProductDistributionBrandDetail''),ROOT(''ProductDistributionBrandDetails''),TYPE'

INSERT INTO @sql
EXEC (@sql2)

SELECT *
FROM @sql

答案 2 :(得分:0)

请参阅此链接的参考资料,它将向您展示如何使用输出参数

https://support.microsoft.com/en-us/kb/262499