使用 XML 架构

SMO 中的 XML 编程仅限于提供 XML 数据类型、XML 命名空间和对 XML 数据类型列的简单索引。

Microsoft SQL Server 为 XML 文档实例提供本机存储。 通过 XML 架构可定义复杂的 XML 数据类型,这些类型可用于验证 XML 文档以确保数据完整性。 XML 架构在 XmlSchemaCollection 对象中定义。

示例

若要使用所提供的任何代码示例,您必须选择创建应用程序所需的编程环境、编程模板和编程语言。 有关详细信息,请参阅 在 Visual Studio .NET 中创建 Visual Basic SMO 项目 或在 Visual Studio .NET 中创建 Visual C# SMO 项目

在 Visual Basic 中创建 XML 架构

此代码示例演示如何使用 XmlSchemaCollection 对象创建 XML 架构。 定义 XML 架构集合的 Text 属性包含多个双引号。 这些双引号将由 chr(34) 字符串替换。

在 Visual C# 中创建 XML 架构

此代码示例演示如何使用 XmlSchemaCollection 对象创建 XML 架构。 定义 XML 架构集合的 Text 属性包含多个双引号。 这些双引号将由 chr(34) 字符串替换。

{  
            //Connect to the local, default instance of SQL Server.   
            Server srv = default(Server);  
            srv = new Server();  
            //Reference the AdventureWorks2012 database.   
            Database db = default(Database);  
            db = srv.Databases["AdventureWorks2012"];  
            //Define an XmlSchemaCollection object by supplying the parent  
            // database and name arguments in the constructor.   
            XmlSchemaCollection xsc = default(XmlSchemaCollection);  
            xsc = new XmlSchemaCollection(db, "MySampleCollection");  
            xsc.Text = "<schema xmlns=" + Strings.Chr(34) + "http://www.w3.org/2001/XMLSchema" + Strings.Chr(34) + " xmlns:ns=" + Strings.Chr(34) + "http://ns" + Strings.Chr(34) + "><element name=" + Strings.Chr(34) + "e" + Strings.Chr(34) + " type=" + Strings.Chr(34) + "dateTime" + Strings.Chr(34) + "/></schema>";  
            //Create the XML schema collection on the instance of SQL Server.   
            xsc.Create();  
        }  

在 PowerShell 中创建 XML 架构

此代码示例演示如何使用 XmlSchemaCollection 对象创建 XML 架构。 定义 XML 架构集合的 Text 属性包含多个双引号。 这些双引号将由 chr(34) 字符串替换。

#Get a server object which corresponds to the default instance replace LocalMachine with the physical server  
cd \sql\LocalHost  
$srv = Get-Item default  
  
#Reference the AdventureWorks database.  
$db = $srv.Databases["AdventureWorks2012"]  
  
#Create a new schema collection  
$xsc = New-Object -TypeName Microsoft.SqlServer.Management.SMO.XmlSchemaCollection `  
-argumentlist $db,"MySampleCollection"  
  
#Add the xml  
$dq = '"' # the double quote character  
$xsc.Text = "<schema xmlns=" + $dq + "http://www.w3.org/2001/XMLSchema" + $dq + `  
"  xmlns:ns=" + $dq + "http://ns" + $dq + "><element name=" + $dq + "e" + $dq +`  
 " type=" + $dq + "dateTime" + $dq + "/></schema>"  
  
#Create the XML schema collection on the instance of SQL Server.  
$xsc.Create()