Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting XML Schema from MS SQL Database

Is it possible to generate a XML Schema of a Database programatically with .Net and C#? I want to look into NDbUnit but for big databases it would not really be feasible to make a Schema manually?

like image 943
Damien Avatar asked Nov 18 '08 13:11

Damien


People also ask

Can you convert SQL to XML?

With SQL Server Management Studio, you can save your SQL database as CSV and then you can convert the database files to XML, PDF or other formats as you like.

What is XML Schema collection in SQL Server?

The XML schema collection is a metadata entity like a table in the database. You can create, modify, and drop them. Schemas specified in a CREATE XML SCHEMA COLLECTION (Transact-SQL) statement are automatically imported into the newly created XML schema collection object.

What is XSD in database?

XML Schema Definition or XSD is a recommendation by the World Wide Web Consortium (W3C) to describe and validate the structure and content of an XML document. It is primarily used to define the elements, attributes and data types the document can contain.

How to work with XML in SQL Server?

To create a SQL table using XML elements, all you have to do is to change the mode value of the OPENXML function to 2 and change the name of the attributes to the name of the element you want to retrieve.


2 Answers

Is it possible to generate a XML Schema from a Database?

It sure is, XMLSpy can generate XML Schema from a database.

There's another way, though I've never tested it:

create table Person
(
Age int not NULL check( Age > 0) ,
Height numeric(10,2) not NULL check( Height > 5),
Gender varchar(5) not null check( Gender in ('M', 'F', 'O')),
BirthDate datetime null,
)

DECLARE @schema xml
SET @schema = (SELECT * FROM Person FOR XML AUTO, ELEMENTS, XMLSCHEMA('PersonSchema'))
select @schema
like image 113
George Stocker Avatar answered Oct 15 '22 21:10

George Stocker


I could do it like this:

DataSet results = new DataSet();

SqlCommand command = new SqlCommand("SELECT * FROM table", new SqlConnection(connectionString));

SqlDataAdapter sqlAdapter = new SqlDataAdapter(command);

sqlAdapter.FillSchema(results, SchemaType.Mapped);//Fills dataset with schema from query
results.WriteXmlSchema(mySchema);

Problem is, how could I adapt this method so that it could be used with a indeterminate amount of tables? Without building up a string though concatenation which is not exactly ideal!

like image 27
Damien Avatar answered Oct 15 '22 21:10

Damien