Click here to Skip to main content
6,293,171 members and growing! (11,732 online)
Email Password   helpLost your password?
Database » Database » General     Intermediate

Generate SQL INSERT commands Programmatically

By Ian Semmel

A class for automatically generating SQL INSERT for Typed Datasets
C#, Windows, .NET, SQL Server, Visual Studio, ADO.NET, DBA, Dev
Posted:20 Jun 2006
Updated:29 Jun 2006
Views:92,892
Bookmarked:31 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
11 votes for this article.
Popularity: 3.31 Rating: 3.17 out of 5
3 votes, 27.3%
1
1 vote, 9.1%
2
1 vote, 9.1%
3
3 votes, 27.3%
4
3 votes, 27.3%
5

Introduction

When you use TableAdapters in C#, VS generates INSERT, SELECT and UPDATE etc commands for you.

Other commands can be added by going into DataSet Designer and adding commands via the Add SQL Wizard.

Sometimes, however, you need additional SQL commands that contain a complete list of all the fields in the DataSet. You would also like these lists to be automatically updated whenever a change is made to the Database.

The code presented here does this by using functions in the Designer code to generate such strings.

Background

 I actually developed these functions because I needed to INSERT rows into a database and get the value of the Identity column on the fly as I tab through a DataGridView adding new rows.

Note that this has only been developed for simple functions, but the basics are generally applicable tho other applications.

Description

 

The file GenerateSQL.cs contains code for a static class GenerateSQL which has the following functions

  • public static string BuildAllFieldsSQL ( DataTable table )
    Returns a list of all the columns in the DataTable in SQL format which can be used in a SELECT command etc
    eg CustomerID, CustomerName, ....

  • public static string BuildInsertSQL ( DataTable table )
    Returns an INSERT command with an optional SELECT CAST statement to get the SCOPE_IDENTITY is required eg
    INSERT INTO tableName ( CustomerName,...) VALUES (@CustomerName,...); SELECT CAST(scope_identity() AS int )
    (Note that in this example, CustomerID is an Identity so it isn't included in the string

  • public static SqlCommand CreateInsertCommand ( DataRow row )
    Given a DataRow, creates an instance of SqlCommand to insert the data into the DataSet

  • public static object InsertDataRow ( DataRow row, string connectionString )
    Given the DataRow and a connection string, creates the SqlCommand as above and executes it, returning the identity of the record

    For example, if dataset designer has defined a row like
    QfrsDataSet.MembersRow row;

    I can insert it into the database, getting the identity, with the statement
    int id = (int) GenSQL.GenerateSQL.InsertDataRow ( row, connectionString );


using System;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;

namespace GenSQL
{
  public static class GenerateSQL
  {
    // Returns a string containing all the fields in the table

    public static string BuildAllFieldsSQL ( DataTable table )
    {
      string sql = "";
      foreach ( DataColumn column in table.Columns )
      {
        if ( sql.Length > 0 )
          sql += ", ";
         sql += column.ColumnName;
      }
      return sql;
                }

    // Returns a SQL INSERT command. Assumes autoincrement is identity (optional)

  public static string BuildInsertSQL ( DataTable table )
  {
    StringBuilder sql = new StringBuilder ( "INSERT INTO " + table.TableName + " (" );
    StringBuilder values = new StringBuilder ( "VALUES (" );
    bool bFirst = true;
    bool bIdentity = false;
    string identityType = null;

    foreach ( DataColumn column in table.Columns )
    {
      if ( column.AutoIncrement )
      {
        bIdentity = true;

        switch ( column.DataType.Name )
        {
          case "Int16":
            identityType = "smallint";
            break;
          case "SByte":
            identityType = "tinyint";
            break;
          case "Int64":
            identityType = "bigint";
            break;
          case "Decimal":
            identityType = "decimal";
            break;
          default:
            identityType = "int";
          break;
         }
      }
      else
      {
        if ( bFirst )
          bFirst = false;
        else
        {
          sql.Append ( ", " );
          values.Append ( ", " );
        }

        sql.Append ( column.ColumnName );
       values.Append ( "@" );
        values.Append ( column.ColumnName );
      }
    }
    sql.Append ( ") " );
    sql.Append ( values.ToString () );
    sql.Append ( ")" );

    if ( bIdentity )
    {
      sql.Append ( "; SELECT CAST(scope_identity() AS " );
      sql.Append ( identityType );
      sql.Append ( ")" );
    }

    return sql.ToString (); ;
  }


    // Creates a SqlParameter and adds it to the command

    public static void InsertParameter ( SqlCommand command,
                                         string parameterName,
                                         string sourceColumn,
                                         object value )
    {
      SqlParameter parameter = new SqlParameter ( parameterName, value );

      parameter.Direction = ParameterDirection.Input;
      parameter.ParameterName = parameterName;
      parameter.SourceColumn = sourceColumn;
      parameter.SourceVersion = DataRowVersion.Current;

      command.Parameters.Add ( parameter );
    }

    // Creates a SqlCommand for inserting a DataRow
    public static SqlCommand CreateInsertCommand ( DataRow row )
    {
      DataTable table = row.Table;
      string sql = BuildInsertSQL ( table );
      SqlCommand command = new SqlCommand ( sql );
      command.CommandType = System.Data.CommandType.Text;

      foreach ( DataColumn column in table.Columns )
      {
        if ( !column.AutoIncrement )
        {
          string parameterName = "@" + column.ColumnName;
          InsertParameter ( command, parameterName, column.ColumnName, row [ column.ColumnName ] );
        }
      }
      return command;
    }

    // Inserts the DataRow for the connection, returning the identity
    public static object InsertDataRow ( DataRow row, string connectionString )
    {
      SqlCommand command = CreateInsertCommand ( row );

      using ( SqlConnection connection = new SqlConnection ( connectionString ) )
      {
        command.Connection = connection;
        command.CommandType = System.Data.CommandType.Text;
        connection.Open ();
        return command.ExecuteScalar ();
      }
    }

  }
}

Using the Code

Just include the source file in your program and call the functions

The (extremely basic) sample program uses the Northwind code files, but does not connect to it.



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

Ian Semmel


Member
I have been programming for about 100 years (42 actually) and have just moved in to C# and SQL.

My main work nowdays involves MFC, but I do a bit of Linux/Unix stuff in C++.
Occupation: Web Developer
Location: Australia Australia

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 24 of 24 (Total in Forum: 24) (Refresh)FirstPrevNext
GeneralUnable to use InsertDataRow Pinmemberkellylc22:26 20 Sep '07  
GeneralRe: Unable to use InsertDataRow PinmemberIan Semmel11:16 25 Sep '07  
GeneralVisual Basic Version of the Code (included) PinmemberDan_Bruton16:55 5 Aug '07  
GeneralThank You PinmemberLev Vayner.5:45 31 Jul '07  
Questiondestination field is of a different data type Pinmemberkissa499:23 29 Jun '07  
Generalinsert datatable into SQL SERVER table using single query Pinmemberrajnish_haldiya23:48 12 Jun '07  
GeneralRe: insert datatable into SQL SERVER table using single query PinmemberIan Semmel11:28 13 Jun '07  
GeneralRe: insert datatable into SQL SERVER table using single query Pinmemberrajnish_haldiya1:26 14 Jun '07  
GeneralRe: insert datatable into SQL SERVER table using single query PinmemberLev Vayner.11:01 30 Jul '07  
GeneralRe: insert datatable into SQL SERVER table using single query Pinmemberrajnish_haldiya22:06 31 Jul '07  
GeneralRe: insert datatable into SQL SERVER table using single query PinmemberLev Vayner.6:30 24 Sep '07  
GeneralUsing GUID Pinmemberppro15:54 2 Feb '07  
QuestionProblem with Identity Pinmembergregoryayca5:10 29 Nov '06  
GeneralWhat about binary data? PinmemberMcGahanFL10:46 20 Oct '06  
NewsTry SqlCommandBuilder class PinmemberAbishek Bellamkonda21:36 25 Jun '06  
GeneralRe: Try SqlCommandBuilder class PinmemberIan Semmel22:29 27 Jun '06  
GeneralRe: Try SqlCommandBuilder class PinmemberAbishek Bellamkonda22:43 27 Jun '06  
GeneralRe: Try SqlCommandBuilder class PinmemberStumper4:45 7 Jul '06  
GeneralStringBuilder PinmemberSteve Hansen2:11 21 Jun '06  
GeneralRe: StringBuilder PinmemberBernhard Hofmann2:54 21 Jun '06  
Generalone question.. PinmemberGuido_d23:43 20 Jun '06  
GeneralRe: one question.. PinmemberAbishek Bellamkonda21:27 25 Jun '06  
GeneralRe: one question.. PinmemberIan Semmel22:33 27 Jun '06  
GeneralRe: one question.. Pinmemberstreetworm12:50 4 Aug '06  

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

PermaLink | Privacy | Terms of Use
Last Updated: 29 Jun 2006
Editor:
Copyright 2006 by Ian Semmel
Everything else Copyright © CodeProject, 1999-2009
Web11 | Advertise on the Code Project