views:

41

answers:

1

I have to query a view and include only those columns which are defined in the XML which comes as a parameter to my SP. Can i include that XML in select clause and extract all columns defined in that XML. Please tell a way to do this.

XML format is

 <Columns>
   <Column Name="CustomerID"/>
   <Column Name="CustomerName"/>
   <Column Name="Customerstate"/>
 </Columns>

I want to put these columns in select list.

 SELECT row.value('@Name', 'varchar(200)')
 FROM   @varXML.nodes('Columns/Column') AS d (row) FROM JobListingDetails
A: 

I'm not sure why you'd do this rather than allow the client application to filter the rows for itself, but if you must do it, you need dynamic SQL:

DECLARE @varXML XML
DECLARE @columnList NVARCHAR(MAX)

SET @varXML = 
' <Columns>
   <Column Name="CustomerID"/>
   <Column Name="CustomerName"/>
   <Column Name="Customerstate"/>
 </Columns>
'

SET @columnList = 
 (SELECT row.value('@Name', 'varchar(200)') + ','
  FROM   @varXML.nodes('Columns/Column') AS d (row)
  FOR XML PATH('')
 )

--SELECT @columnList

SET @columnList = 'SELECT ' + LEFT(@columnList, LEN(@columnList) - 1) + ' FROM JobListingDetails'

EXEC sp_executesql @columnList
Ed Harper