开发者

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"/>
   <开发者_StackOverflow;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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜