現在XML使用的越來越多,在SQL Server表中我們可以建立XML列儲存資料。 昨天在論壇看到有人說建立了一個預存程序處理XML,但是插入目標表的時候報錯,而報的錯誤不詳細。 其實這個問題的根本原因是XML的資料有問題,應該在插入的時候對輸入的資料進行驗證(對於使用者輸入的資料一定要做驗證)。
其實SQL Server已經提供了XML Schema驗證,下面我們看一個例子:
--建立XML Schema Collation
CREATE XML
SCHEMA COLLECTION myCollection
AS
'<xsd:schemaxmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://myBooks"
elementFormDefault="qualified"
targetNamespace="http://myBooks">
<xsd:element name="bookstore"type="bookstoreType" />
<xsd:complexTypename="bookstoreType">
<xsd:sequencemaxOccurs="unbounded">
<xsd:element name="book"type="bookType" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="bookType">
<xsd:sequence>
<xsd:element name="title"type="xsd:string" />
<xsd:element name="author"type="authorName" />
<xsd:element name="price"type="xsd:decimal" />
</xsd:sequence>
<xsd:attribute name="genre"type="xsd:string" />
<xsd:attributename="publicationdate" type="xsd:string" />
<xsd:attribute name="ISBN"type="xsd:string" />
</xsd:complexType>
<xsd:complexTypename="authorName">
<xsd:sequence>
<xsd:elementname="first-name" type="xsd:string" />
<xsd:element name="last-name"type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:schema>'
--建立表用上面建立的XML Schema做驗證
create table XmlCatalog ( ID
int, MyInfoXML
(CONTENT myCollection));
--插入資料
INSERT XmlCatalogVALUES(1,'<?xmlversion="1.0"?>
<bookstorexmlns="http://myBooks">
<book genre="autobiography"publicationdate="1981"
ISBN="1-861003-11-0">
<title>The Autobiography of BenjaminFranklin</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Franklin</last-name>
</author>
<price>8.99</price>
</book>
<book genre="novel"publicationdate="1967"
ISBN="0-201-63361-2">
<title>The ConfidenceMan</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
</book>
<book genre="philosophy"publicationdate="1991"
ISBN="1-861001-57-6">
<title>The Gorgias</title>
<author>
<first-name>Sidas</first-name>
<last-name>Plato</last-name>
</author>
<price>9.99</price>
</book>
</bookstore>
')
--如果XML格式有問題報錯
INSERT XmlCatalogVALUES(1,'<?xmlversion="1.0"?>
<book genre="philosophy"publicationdate="1991"
ISBN="1-861001-57-6">
<title>The Gorgias</title>
<author>
<first-name>Sidas</first-name>
<last-name>Plato</last-name>
</author>
<price>9.99</price>
</book>
</bookstore>
')
Msg 6913, Level 16, State 1, Line 1
XML Validation: Declaration not found for element 'book'.Location: /*:book[1]
這樣的錯誤是非常清楚的,可以很快的協助我們Troubleshooting.