Click here to Skip to main content
Licence CPOL
First Posted 20 Jun 2006
Views 141,672
Downloads 963
Bookmarked 49 times

Generate SQL INSERT commands programmatically

By | 29 Jun 2006 | Article
A class for automatically generating SQL INSERT for Typed Datasets.
 
Part of The SQL Zone sponsored by
See Also

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 the 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 for other applications.

Description

The file GenerateSQL.cs contains the 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. E.g.: CustomerID, CustomerName, ....

  • public static string BuildInsertSQL ( DataTable table )
  • Returns an INSERT command with an optional SELECT CAST statement to get the SCOPE_IDENTITY if required. E.g.: 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 the Dataset Sesigner 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 );

Here is the complete code:

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Ian Semmel

Web Developer

Australia Australia

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++.

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. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Suggestion1 small change Pinmemberleote1:22 11 Apr '12  
GeneralMy vote of 5 Pinmembereibbed15:26 10 Aug '11  
GeneralThanks a lot Pinmemberashu khanna7:43 22 Apr '11  
GeneralUnable to use InsertDataRow Pinmemberkellylc21:26 20 Sep '07  
GeneralRe: Unable to use InsertDataRow PinmemberIan Semmel10:16 25 Sep '07  
GeneralVisual Basic Version of the Code (included) PinmemberDan_Bruton15:55 5 Aug '07  
Thanks for the *very* useful code. I have coverted it from C# to Visual Basic and included it below. I also modified the code to handle field names with spaces in them (when we do not have a choice).
 

'Usage
InsertDataRow(dr,str)
 

 
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.text
 
Public Class SQLTools
 
' Inserts the DataRow for the connection, returning the identity
Public Function InsertDataRow(ByVal row As DataRow, ByVal connectionString As String) As String
Dim command As SqlCommand = CreateInsertCommand(row)
'Dim connection As SqlConnection
Using connection As SqlConnection = New SqlConnection(connectionString)
command.Connection = connection
command.CommandType = System.Data.CommandType.Text
connection.Open()
Return command.ExecuteScalar()
End Using
End Function
 
Public Function BuildAllFieldsSQL(ByVal table As DataTable) As String
Dim sql As String = ""
Dim dc As DataColumn
For Each dc In table.Columns
If (sql.Length > 0) Then sql += ", "
sql += dc.ColumnName
Next
Return sql
End Function
 
' Returns a SQL INSERT command. Assumes autoincrement is identity (optional)
Public Function BuildInsertSQL(ByVal table As DataTable) As String
Dim sql As StringBuilder = New StringBuilder("INSERT INTO " + table.TableName + " (")
Dim values As StringBuilder = New StringBuilder("VALUES (")
Dim bFirst As Boolean = True
Dim bIdentity As Boolean = False
Dim identityType As String = ""
Dim dc As DataColumn
For Each dc In table.Columns
If (dc.AutoIncrement) Then
bIdentity = True
Select Case dc.DataType.Name
Case "Int16"
identityType = "smallint"
Case "SByte"
identityType = "tinyint"
Case "Int64"
identityType = "bigint"
Case "Decimal"
identityType = "decimal"
Case Else
identityType = "int"
End Select
Else
If (bFirst) Then
bFirst = False
Else
sql.Append(", ")
values.Append(", ")
End If
 
sql.Append("[" & dc.ColumnName & "]")
'sql.Append(Replace(dc.ColumnName, " ", ""))
values.Append("@")
'values.Append(dc.ColumnName)
values.Append(Replace(dc.ColumnName, " ", ""))
 
End If
Next
sql.Append(") ")
sql.Append(values.ToString())
sql.Append(")")
 
If (bIdentity) Then
sql.Append("; SELECT CAST(scope_identity() AS ")
sql.Append(identityType)
sql.Append(")")
End If
Return sql.ToString()
End Function
 

' Creates a SqlParameter and adds it to the command
Public Function InsertParameter(ByVal command As SqlCommand, ByVal parameterName As String, ByVal sourceColumn As String, ByVal value As Object) As SqlCommand
Dim parameter As SqlParameter
parameter = New SqlParameter(parameterName, value)
 
parameter.Direction = ParameterDirection.Input
parameter.ParameterName = parameterName
parameter.SourceColumn = sourceColumn
parameter.SourceVersion = DataRowVersion.Current
 
command.Parameters.Add(parameter)
Return command
End Function
 

' Creates a SqlCommand for inserting a DataRow
Public Function CreateInsertCommand(ByVal row As DataRow) As SqlCommand
Dim table As DataTable = row.Table
Dim sql As String = BuildInsertSQL(table)
Dim command As SqlCommand = New SqlCommand(sql)
command.CommandType = System.Data.CommandType.Text
Dim dc As DataColumn
For Each dc In table.Columns
If (Not dc.AutoIncrement) Then
Dim parameterName As String = "@" + Replace(dc.ColumnName, " ", "")
InsertParameter(command, parameterName, dc.ColumnName, row(dc.ColumnName))
End If
next
Return command
End Function
 
End Class

GeneralThank You PinmemberLev Vayner.4:45 31 Jul '07  
Questiondestination field is of a different data type Pinmemberkissa498:23 29 Jun '07  
Generalinsert datatable into SQL SERVER table using single query Pinmemberrajnish_haldiya22:48 12 Jun '07  
GeneralRe: insert datatable into SQL SERVER table using single query PinmemberIan Semmel10:28 13 Jun '07  
GeneralRe: insert datatable into SQL SERVER table using single query Pinmemberrajnish_haldiya0:26 14 Jun '07  
GeneralRe: insert datatable into SQL SERVER table using single query PinmemberLev Vayner.10:01 30 Jul '07  
GeneralRe: insert datatable into SQL SERVER table using single query Pinmemberrajnish_haldiya21:06 31 Jul '07  
GeneralRe: insert datatable into SQL SERVER table using single query PinmemberLev Vayner.5:30 24 Sep '07  
GeneralUsing GUID Pinmemberppro14:54 2 Feb '07  
QuestionProblem with Identity Pinmembergregoryayca4:10 29 Nov '06  
QuestionWhat about binary data? PinmemberMcGahanFL9:46 20 Oct '06  
NewsTry SqlCommandBuilder class PinmemberAbishek Bellamkonda20:36 25 Jun '06  
GeneralRe: Try SqlCommandBuilder class PinmemberIan Semmel21:29 27 Jun '06  
GeneralRe: Try SqlCommandBuilder class PinmemberAbishek Bellamkonda21:43 27 Jun '06  
GeneralRe: Try SqlCommandBuilder class PinmemberStumper3:45 7 Jul '06  
GeneralStringBuilder PinmemberSteve Hansen1:11 21 Jun '06  
GeneralRe: StringBuilder PinmemberBernhard Hofmann1:54 21 Jun '06  
Generalone question.. PinmemberGuido_d22:43 20 Jun '06  
GeneralRe: one question.. PinmemberAbishek Bellamkonda20:27 25 Jun '06  

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120529.1 | Last Updated 29 Jun 2006
Article Copyright 2006 by Ian Semmel
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid