XML Select Example (Legacy)The XML Select control works in conjunction with either an External Data Source Control or a Database Get control to render the results of a query as a grid or drop down list. Items selected in the grid can then be used again in further queries to present related data.
In the following example, we want to display the number of Reps available in each county on our script page.
The following SQL Statement is used to count the reps in each county:
This gives us the table we wish to display on our script page, however we now need to embed XML into the SQL statement in order to define how it will be displayed, the result of which will look like this:
<xml>
<columns>
<column><name>County</name></column>
<column><name>Reps</name></column>
</columns>
<rows>
<row><county>Bristol</county><No_Reps>6</Reps></row>
<row><county>Essex</county><No_Reps>6</Reps></row>
<row><county>Leics</county><No_Reps>3</Reps></row>
<row><county>Suffolk</county><No_Reps>11</Reps></row>
<row><county>Yorkshire</county><No_Reps>6</Reps></row>
</rows>
</xml>
We now have to combine the two in a statement that results in a string containing the XML output that the XML Select can render in our script page. The statement will be placed in either a Database Get control, or an External Data Source control depending on when you want the query to run.
You must make sure that the Column Names you specify in step 5, exactly match the column names in your SQL statement. In the example above, the database field "county" does not match the required column name of "County". In this case, this has been overcome by giving the column an alias in the SQL statement to which matches the column specified in the XML. Alternatively you could re-label the columns in XML.
BEGIN
SET NOCOUNT ON
Declare @MyRowVariable nvarchar(max)
Declare @MyColumnVariable nvarchar(max)
Set @MyColumnVariable = ''
Set @MyRowVariable = ''
Set @MyColumnVariable = @MyColumnVariable+'<column><name>County</name><reference>True</reference><display></display></column><column><name>Reps</name><reference>False</reference><display></display></column>'
Set @MyRowVariable = @MyRowVariable+(Select county as County, count(id) as Reps from TrainingData group by county
for xml path('row'))
END
Select '<xml><columns>' + @MyColumnVariable + '</columns><rows>' + @MyRowVariable + '</rows></xml>' as anythingyoulike
|