简体   繁体   中英

Dynamic select clause in SQL Server from XML

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM