XML Select with Microsoft SqlServer 2000
Mar 4th, 2007 by Onyrix 1,204 Views |
Email This Post
|
Print This Post
Avete mai provato ad aggiungere la clausola FOR XML AUTO in fondo a una select fatta su SQLServer 2000?
Provate, otterete come risposta un recordset di una riga una colonna con dentro una bella stringona che è un XML Fragment contenente la risposta alla Vs query.
La sintassi generale per avere resultset in formato XML fragment è:
Code:
Esempio 1
SELECT colonne_da_visualizzare
FROM nome_tabella
WHERE condizioni_di_ricerca
FOR XML AUTO | RAW | EXPLICIT [, XMLDATA] [, ELEMENTS] [, BINARY BASE64]
restituisce le righe come elementi e le colonne come attributi, esempio:
SELECT nome,cognome FROM utenti FOR XML AUTO
Code:
Esempio 2
<utenti nome=”Dino” cognome=”Olivieri” />
<utenti nome=”Enrico” cognome=”Porta” />
RAW sostituisce il nome riga della tabella con row sia che usi gli elements (vedi esempio successivo) sia che non li usi:
SELECT nome,cognome FROM utenti FOR XML RAW
Code:
Esempio 3
<row nome=”Enrico” cognome=”Porta” />
SELECT nome,cognome FROM utenti FOR XML AUTO, ELEMENTS
restituisce le righe come elementi e le colonne come elementi figlio, esempio:
Code:
<utenti>
<nome>Dino</nome>
<cognome>Olivieri</cognome>
</utenti>
<utenti>
<nome>Enrico</nome>
<cognome>Porta</cognome>
</utenti>
Esempio 4
Ecco come ottenere un Fragment TR, TD con tanto di intestazione pronto da impaginare in un documento HTML
Code:
SELECT TOP 1 ‘ID GRUPPO’ as td, ‘NOME GRUPPO’ AS td FROM table_groups AS tr
UNION ALL
SELECT TOP 10 CONVERT(varchar, idgroup) AS td, group_name AS td FROM table_groups AS tr
FOR XML AUTO, ELEMENTS

del.icio.us
Digg
Furl
Reddit
Technorati