5,693,062 members and growing! (16,521 online)
Email Password   helpLost your password?
Database » Database » General     Intermediate

Generate Insertion Scripts using .Net 2.0

By Benedict Chan

Using .Net 2.0 to get SQL Server Schema and generating Insertion Statements
C# 2.0, C#Windows, .NET, .NET 2.0, Win2K, WinXP, WinForms, SQL 2000, VS2005, SQL Server, Visual Studio, DBA, Dev

Posted: 23 Jul 2007
Updated: 23 Jul 2007
Views: 9,680
Bookmarked: 16 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
4 votes for this Article.
Popularity: 2.78 Rating: 4.62 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
2 votes, 50.0%
4
2 votes, 50.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article
Screenshot - Preview.jpg

Introduction

Recently I have to modify some data in SQL Server and insert them into other databases. The approach is to get the data from the source database. Modify them in a grid and generate Insertion Statements from the the gird for later use.

Background

The features for getting SQL Server schema in .Net 2.0 is very useful and easy to use. And the task to generate scripts becomes very easy if you can get the schema.

Using the code

To get SQL Server Instance

            DataTable table = System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources();
            DataView view = new DataView(table, string.Empty, "ServerName", DataViewRowState.Added);
            cbx_ServerList.DataSource = view;
            cbx_ServerList.DisplayMember = "ServerName";<o:p /> 

To get list of SQL Server Databases

            DataTable table = conn.GetSchema(SqlClientMetaDataCollectionNames.Databases);
            cbx_DatabaseList.DataSource = table;
            cbx_DatabaseList.DisplayMember = "database_name";<o:p /> 

To get list of Tables

            DataTable table = conn.GetSchema(SqlClientMetaDataCollectionNames.Tables, new string[] { null, null, null, "BASE TABLE" });
            cbx_TableList.DataSource = table;
            cbx_TableList.DisplayMember = "TABLE_NAME";<o:p /> 

To get list of Views

            DataTable table = conn.GetSchema(SqlClientMetaDataCollectionNames.Tables, new string[] { null, null, null, "VIEW" });
            cbx_ViewList.DataSource = table;
            cbx_ViewList.DisplayMember = "TABLE_NAME";<o:p /> 

To get list of Columns

Some types are ignored because I don't really need this to be exported. And, it looks strange to export an image to a text file right?

            private const string FILTER_COLUMN_TYPE = "data_type NOT IN ('uniqueidentifier', 'timestamp', 'image')"; <o:p /> 
            DataTable columnsTable = conn.GetSchema(SqlClientMetaDataCollectionNames.Columns, new string[] { null, null, tableName });
            DataView columnsView = new DataView(columnsTable, FILTER_COLUMN_TYPE, "ordinal_position", DataViewRowState.Added);<o:p /> 

Script Generation

        private static string GenerateDataRowInsertSQLScript(string SQLTableName, DataRow row, ArrayList includedColumnNames)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(" INSERT INTO [").Append(SQLTableName).Append("] ( ");
            for (int cnt = 0; cnt < includedColumnNames.Count; cnt++)
            {
                if (cnt != 0)
                    builder.Append(", ");
                builder.Append("[").Append(includedColumnNames[cnt].ToString()).Append("]");
            }
            builder.Append(" ) ").Append(Environment.NewLine);

            builder.Append(" VALUES ( ");
            for (int cnt = 0; cnt < includedColumnNames.Count; cnt++)
            {
                if (cnt != 0)
                    builder.Append(", ");

                string columnName = includedColumnNames[cnt].ToString();
                builder.Append(SqlHelper.ToSQLString(row[columnName], row.Table.Columns[columnName].DataType));
            }
            builder.Append(" ) ").Append(Environment.NewLine).Append(Environment.NewLine);

            return builder.ToString();
        } <o:p /> 

The Demo

Input the connection details, and choose the corresponding Table.

Screenshot - Login.jpg

The "Select Script" button will generate a SELECT statement, it is just for convenience. You can add a WHERE CAUSE after that as well.

Screenshot - SelectStatement.jpg


Press "Execute" button and you will get the result data set in the gird.

Screenshot - OriginalData.jpg


You can then modify the data as you like.
By choosing the "Columns", you can do a Re-Ordering or a Replacement function in the grid if you like.

Screenshot - ModifiedData.jpg

Press the "Preview" button to get the Insertion Script.

Screenshot - Preview.jpg

Conclusion

This is just a simple project to show you how to get the schema from SQL Server using .Net 2.0.

A note is that since I didn't capture what you have input in the Select Script Box. And I don't know what is the TABLE NAME by just the Data Set returned. Therefore you need to choose the correct TABLE NAME before generating the Insertion Scripts.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Benedict Chan



Occupation: Web Developer
Location: Hong Kong Hong Kong

Other popular Database articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 3 of 3 (Total in Forum: 3) (Refresh)FirstPrevNext
GeneralA Nice ToolmemberYelihs23:44 24 Jul '07  
GeneralPerformance Issuememberchris33880:12 24 Jul '07  
GeneralRe: Performance IssuememberBenedict Chan1:06 24 Jul '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 23 Jul 2007
Editor:
Copyright 2007 by Benedict Chan
Everything else Copyright © CodeProject, 1999-2008
Web20 | Advertise on the Code Project