0

How do I assign the results of an exec command to a variable. like the below, so when I do select @sql2 I get the result of the executed 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            
user3266033
  • 157
  • 1
  • 2
  • 12
  • Seems similar to http://stackoverflow.com/questions/803211/how-to-get-sp-executesql-result-into-a-variable – P.Salmon Jun 07 '16 at 10:31

3 Answers3

2

Use an output param:

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
Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

You can use Table Variables. Try like this,

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
StackUser
  • 5,370
  • 2
  • 24
  • 44
0

Please see reference from this link it will show you how to use output parameters

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

Myo Myint Aung
  • 147
  • 1
  • 3
  • Your answer in itself does not provide and answer to the question, links should supplement an answer, not be the entirety of it. So although the link you have posted is useful and more or less answers the question, your answer should at the very least summarise the article, and include bits relevant to this particular question, so that in the event that the website moves or goes down, your answer still remains useful to future visitors. – GarethD Jun 07 '16 at 10:47