views:

202

answers:

2

i want to generate scripts for database objects, e.g.

  • tables
  • views
  • stored procedures
  • functions

Since:

are not installed on a fresh install of:

  • Windows XP
  • Windows Vista
  • Windows 7

nor are they redistributable, they are not an option (it will run on a customer's machine).

Is there any source code that converts SELECTs from system tables into associated scripts?


i'll start us off with the pseudo-code that scripts a stored procedures, views, triggers, or user-defined functions:

String GetStoredProcedureScript(String storedProcedureName)
{
   return GetHelpText(storedProcedureName);
}

String GetViewScript(String viewName)
{
   return GetHelpText(viewName);
}

String GetTriggerScript(String triggerName)
{
   return GetHelpText(storedProcedureName);
}

String GetUserDefinedFunctionScript(String userDefinedFunctionName)
{
   return GetHelpText(userDefinedFunctionName);
}

All which can internally use a single helper function:

String GetHelpText(String objectName)
{
   String szQuery = 'EXECUTE sp_helptext '+QuotedStr(objectName);


   String sql := '';

   using (Recordset rs = connection.Execute(szQuery))
   {
      while not rs.EOF do
      {
         sql = sql+rs['text'];
         rs.Next;
      }
   }

   return sql;
}

Edit: Thanks servicesharvest316 for pointing out sp_helptext. That's why i have a class that abstracts these things away.

+1  A: 

This is the book for you. It explains how to make a code generator that will do what you asked.

I use a modified version for MySql and it worked like a charm. Code Generation in Microsoft .NET

Stéphane
Can you give us a hint of the techniques?
Ian Boyd
This is a multi step process.1- You have to read the metadata from the database (Table, columns, PKey, FKey, Restrictions if you want security). There is always a system table with the data in MySQL the database for that is Information_Schema. 2- You have to make youre template of a typical class in XSLT3- If you want tyou can add a FreeForm XML4- Mash up all this and you'll have a complete classI don't have it with me but I could send you my project if you like.
Stéphane
+1  A: 

Have you tried sp_helptext?

String szQuery = 'EXEC sp_helptext '+QuotedStr(storedProcedureName)
Thanks for sp_helptext. That makes everything done, except tables.
Ian Boyd