Click here to Skip to main content
Click here to Skip to main content

Generate SQL Script Programmatically

By , 8 Sep 2009
 

Introduction

This article will give you an idea of how easily you can generate the SQL server database object script using C#. NET.

Background

This article will be helpful for developers who want to generate the SQL Server database objects script like stored procedure, views, etc.

Using the Code

It’s a very easy way... I hope that you will agree with me that the flexibility of Microsoft products to integrate with your custom application is outstanding. Microsoft SQL Server provides a special stored procedure "sp_helptext", This stored procedure allows you to get the description of a given object.

Here I write a function to get the SQL script from a given object. You just need to provide three parameters:

  • Connection string
  • Object name
  • Object type (I used this to determine whether it's a Table or not)
Syntax
exec sp_helptext 'object'

A sample code example is given below.

Sample Code

public string GetScript(string strConnectionString
                      , string strObject
                      , int ObjType)
{
    string strScript = null;
    int intCounter = 0;
    if (ObjType != 0)
    {
        ObjSqlConnection = new SqlConnection(strConnectionString.Trim());

        try
        {
            ObjDataSet = new DataSet();
            ObjSqlCommand = new SqlCommand("exec sp_helptext 
				[" + strObject + "]", ObjSqlConnection);
            ObjSqlDataAdapter = new SqlDataAdapter();
            ObjSqlDataAdapter.SelectCommand = ObjSqlCommand;
            ObjSqlDataAdapter.Fill(ObjDataSet);

            foreach (DataRow ObjDataRow in ObjDataSet.Tables[0].Rows)
            {
                strScript += Convert.ToString(ObjDataSet.Tables[0].Rows[intCounter][0]);
                intCounter++;
            }
        }
        catch (Exception ex)
        {
           strScript = ex.Message.ToString();
        }
        finally
        {
            ObjSqlDataAdapter = null;
            ObjSqlCommand = null;
            ObjSqlConnection = null;
        }
    }

    return strScript;
}

Points of Interest

The stored procedure sp_helptext will not allow to give you any table description.

Conclusion

I hope that this article will be helpful to you. Enjoy!

History

  • 8th September, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Md. Marufuzzaman
CEO
Bangladesh Bangladesh
He is the founder & CEO of MNH Technologies and working for urban and rural sectors to improve people’s lifestyle, better medical facilities, education, social business etc. He has over ten years of professional experiences in design and developing Client-Server, Multi-Tier, Database, Web based business software solutions, Enterprise Applications, API, WebAPI, Google Analytics implementation, Add-In, Documentation & Technical Writing etc for Windows / Mac using Microsoft SQL Server, Oracle, MySql, PS, C#, VB.NET, ASP.NET, PHP, RoR, Visual Basic etc. He has also more than two years experience in Mobile-VAS (Platform Development).
 
He worked for various software development & technology consulting. His core focus on technologies to create dynamic data-driven systems that add value to your business and dynamic technology consulting that builds advanced solutions for the industries across the various vertices.
 
He also work as a Solution Architect at Dhrupadi Techno Consortium Limited (DTCL) and responsible for analyzing business requirements and offered optimum solutions (multiple options), which would address all current requirements, provide flexibility for future growth and allow smooth transition between old system and new system.
 
He graduated with honors from The University of Asia Pacific, in Computer Science and Engineering. He was awarded as “Most Valuable Professional” (MVP) at 2010 and 2011 by CodeProject.com and also selected as a Mentor of CodeProject.com
 
Specialties: Software Development Management, System Integration, Data Warehouse Architecture, Virtualization.
Follow on   Twitter

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4memberkishore doni28-Aug-12 22:09 
Thanks
GeneralMy vote of 2memberSami Ciit27-Aug-12 1:41 
Call to this function was necessary to be given in an easily understandable way. May be with some simple examples. That is missing. Many like me would be unable to use this function
QuestionThanksmemberdharm777-Aug-12 20:50 
Thanks. It's very usefull
AnswerRe: ThanksmentorMd. Marufuzzaman7-Aug-12 21:04 
Smile | :)
Thanks
Md. Marufuzzaman


I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

QuestionGood workmemberSunasara Imdadhusen31-Aug-11 22:46 
excellent!

sunaSaRa Imdadhusen
+91 99095 44184

AnswerRe: Good workmvpMd. Marufuzzaman1-Sep-11 14:08 
Thanks
Thanks
Md. Marufuzzaman


I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

GeneralKeep goingmemberAndre K11-Apr-11 20:54 
Thanx for your article. It take energy to write something and I say well done for contributing. But, due to the high standard of articles on Code Project, your article need to be upgraded. Do more research, look at other high ranking articles for examples and update your article to make it great.
 
Do not be discouraged by negative comments. Learn from them.
 
Also congratulations in conversion from VB to C#!
GeneralRe: Keep goingmvpMd. Marufuzzaman1-Sep-11 14:07 
Hi Andr:
 
Thanks for your valuable comments; and I will must update some of my articles.
Thanks
Md. Marufuzzaman


I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

GeneralMy vote of 2memberJohn Brett24-Sep-09 5:49 
The coding style is very poor - are you a VB programmer? No understanding of the foreach construct, setting local variables to null on the way out, appalling approach to error handling (opaque to the caller whether the call has succeeded or failed), ObjType appears to be pointless.
Just to be clear, I'm rating the code, not the concept or functionality.
GeneralRe: My vote of 2groupMd. Marufuzzaman28-Sep-09 7:03 
Thanks for your comments...Smile | :) I was a VB programmer and   i m trying to be a good C# programmer....Smile | :)
 
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.


Don't forget to click [Vote] / [Good Answer] on the post(s) that helped you.
 
Thanks
Md. Marufuzzaman

QuestionA bit miffed ???memberEd Bouras15-Sep-09 2:28 
Could you explain how this is "Scripting" an object? It is just providing a point of metadata, right? Also, you say it provides a description of an object but then say later it does not provide a description for tables... could you explain this discrepancy please? And it would have been nice if you included an example of output so that we know what to expect.
 
The way I see it: an article on a potentially useful, but limited scope stored procedure that is not really explained or described in any detail, is mis-titled, and is not adding any value on the subject beyond just letting us be aware of its existence. (oh, I guess you are providing an example of using ADO objects too). Perhaps you could rewrite the article and add some meat to the bones here.
GeneralMy vote of 1memberAndrei Rinea14-Sep-09 22:25 
crap
GeneralMy vote of 1memberPaw Jershauge8-Sep-09 8:36 
I would take a look at this...
SQL Class Shell Generator[^]
GeneralRe: My vote of 1groupMd. Marufuzzaman28-Sep-09 7:06 
Thanks..Smile | :)
 
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.


Don't forget to click [Vote] / [Good Answer] on the post(s) that helped you.
 
Thanks
Md. Marufuzzaman

GeneralGood.memberAbhishek Sur8-Sep-09 8:29 
This one is good, but I was expecting more from this. Initially I thought it would generate Insert, update statements automatically.
 
Another concern, are you sure sp_helptext works with SQL Server CE. I am not sure, but I dont think it does.
 
Anyways, nice article. Hope to find more from you. 4 from me on this. Big Grin | :-D
 
Cheers.
Thumbs Up | :thumbsup: Thumbs Up | :thumbsup:
 
Abhishek Sur

My Latest Articles
Create CLR objects in SQL Server 2005
C# Uncommon Keywords
Read/Write Excel using OleDB

Don't forget to click "Good Answer" if you like to.

GeneralRe: Good.groupMd. Marufuzzaman8-Sep-09 8:36 
Thanks for the comments... You are right on the SQL Server CE.. it a mistake on attribute selection.
 
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.


Don't forget to click [Vote] / [Good Answer] on the post(s) that helped you.
 
Thanks
Md. Marufuzzaman

GeneralRe: Good.memberAbhishek Sur8-Sep-09 22:14 
You are most welcome Thumbs Up | :thumbsup:
 
Abhishek Sur

My Latest Articles
Create CLR objects in SQL Server 2005
C# Uncommon Keywords
Read/Write Excel using OleDB

Don't forget to click "Good Answer" if you like to.

GeneralMy vote of 1membervoloda28-Sep-09 8:25 
What is it about?
GeneralMy vote of 2memberFatih Birkan8-Sep-09 8:14 
"Mobile (PalmOS, iPhone, Android, Blackberry), J2ME"
 
Are they support sql server or C# ? I don't think so.
GeneralRe: My vote of 2groupMd. Marufuzzaman8-Sep-09 8:38 
it a mistake on attribute selection.. Thanks
 
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.


Don't forget to click [Vote] / [Good Answer] on the post(s) that helped you.
 
Thanks
Md. Marufuzzaman

GeneralMy vote of 1memberbrunomsilva8-Sep-09 7:37 
Poor article and misleading title.
GeneralRe: My vote of 1groupMd. Marufuzzaman8-Sep-09 8:24 
I dont believe that... it's about to sharing something...
Thanks for the comments...
 
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.


Don't forget to click [Vote] / [Good Answer] on the post(s) that helped you.
 
Thanks
Md. Marufuzzaman

GeneralMy vote of 1memberhth20008-Sep-09 7:25 
???
GeneralRe: My vote of 1groupMd. Marufuzzaman8-Sep-09 8:20 
!!!
 
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.


Don't forget to click [Vote] / [Good Answer] on the post(s) that helped you.
 
Thanks
Md. Marufuzzaman

GeneralRe: My vote of 1memberaspdotnetdev16-Sep-09 14:06 
Lol, I think I'll use that next time somebody replies to one of my articles with a subject of "my vote of 1" and a body of "" (empty). I'll just reply with an empty message Poke tongue | ;-P
 
Visual Studio is an excellent GUIIDE.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 8 Sep 2009
Article Copyright 2009 by Md. Marufuzzaman
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid