tags:

views:

22

answers:

0

I'm trying to write a sql script that loops through every table in my database and generates an xml schema based on the structure only, not the data.

So far I have this script that loops through the tables and finds which column is the primary key:

select kcu.TABLE_SCHEMA, kcu.TABLE_NAME, kcu.CONSTRAINT_NAME, tc.CONSTRAINT_TYPE,
kcu.COLUMN_NAME, kcu.ORDINAL_POSITION
  from INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc
  join INFORMATION_SCHEMA.KEY_COLUMN_USAGE as kcu
    on kcu.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
   and kcu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
   and kcu.TABLE_SCHEMA = tc.TABLE_SCHEMA
   and kcu.TABLE_NAME = tc.TABLE_NAME
 where tc.CONSTRAINT_TYPE in ( 'PRIMARY KEY', 'UNIQUE' )
 order by kcu.TABLE_SCHEMA, kcu.TABLE_NAME, tc.CONSTRAINT_TYPE, kcu.CONSTRAINT_NAME,     kcu.ORDINAL_POSITION;

I also have this script that creates an xml schema for a particular table. For example, if I have a table called 'foo':

DECLARE @schema xml
SET @schema = (SELECT * FROM [foo] WHERE [foo].ID ='' FOR XML AUTO, ELEMENTS,     XMLSCHEMA('CaseSchema'))
select @schema

The SELECT statement finds all rows with the primary key ID equal to '' (nothing) so that none of the data in the table is selected and generated as xml. This way only the table structure is returned.

My question is, How do I combine these two scripts together?

Thanks