 |
|
 |
Hi, had a error with a database with a field named "check", so made a small change on
public static string BuildInsertSQL ( DataTable table )
changed the
sql.Append ( column.ColumnName );
to
sql.Append ( "[" + column.ColumnName + "]" );
|
|
|
|
 |
|
 |
I was just about to write code to do this exact thing, thank you.
|
|
|
|
 |
|
 |
Thanks Ian,
It saved me hours. At the moment, I was a bit confused how to generate the scripts programatically but this all, did the trick for me.
|
|
|
|
 |
|
 |
Could you provide an example on how to pass a data row to the InsertDataRow function? I obtain a syntax error as following:-
Incorrect syntax near '('.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near '('.
Source Error:
Line 219: command.CommandType = System.Data.CommandType.Text;
Line 220: connection.Open();
Line 221: command.ExecuteScalar ();
Line 222:
Line 223: }
Thanks.
Kelly
|
|
|
|
 |
|
 |
I don't really know what the problem is, but there could be something in your schema that is not handles, eg some sort of sql type. You would really have to debug it and look at the generated sql.
Perhaps it is the parameter name. You could look at the vb version contributed by Dan Bruton below.
|
|
|
|
 |
|
 |
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
|
|
|
|
 |
|
 |
Ian,
Thank you for the article. This is very useful (as I have used it in my app already
|
|
|
|
 |
|
 |
The destination fields in the SQL table that I will be inserting my data into are of all different data types: some are varchar, some are float, some are int. I need to figure out each type and then do a cast on the values im inserting, (they are all saved as strings in my DataTable). How can I figure out, one by one, the data types of the fields so I can do the casting.
Thank you!
Vicky
-- modified at 15:11 Friday 29th June, 2007
|
|
|
|
 |
|
 |
Hi friends,
I have a datatable that is holding the data for an Excel sheet records. Now i want to insert all the data of this datatable to a SQL SERVER database table.
if ordinarily i do it ,then i would need to open and close the database connection for as many times as many rows in datatable.
Is there any way to insert this datatable data to SQL SERVER datatable by a single database insert query.
If it is possible , then could anybody provide the code for it.
Any help will be greatly appritiated...
Many Many Thanks in advance
Rajnish
|
|
|
|
 |
|
 |
Are you using typed datasets ? Well, I think that if you Add the data rows to the table and then call Update on the TableAdapter (or the DataAdapter), it will add the rows (using Insert) and will only open the connection once (if it needs to).
|
|
|
|
 |
|
 |
Many thanks for your suggation..
But could you kindly provide me code for this..
Actually i had tried to do this with DataAdapter.. but could not done it..
Could you kindly provide me code for this..
very thank if you..
Regards
rajnish
|
|
|
|
 |
|
 |
Maybe if you could describe your situation a bit more.. What language (c# w/ .NET 2.0) and What object is holding your data before you attempt to insert into sql server
|
|
|
|
 |
|
 |
First of all thanks alot for your response. My situation is like as follows.
I have a datatable that is holding the data from an Excel sheet records. Now i want to insert all the data of this datatable to a SQL SERVER database table.
if ordinarily i do it ,then i would need to open and close the database connection for as many times as many rows in datatable.
Is there any way to insert this datatable data to SQL SERVER database using a single insert query.
If it is possible , then could you pls provide the code for it.
I am using ASP.NET 1.1 using C#.
Your help is greatly appritiated...
Many Many Thanks in advance
|
|
|
|
 |
|
 |
This should get you started on your way
//Create a dataset
DataSet ds = new DataSet();
//create a data adapter to read from your datasource
OleDbDataAdapter adp = new OleDbDataAdapter("SELECT * FROM MyTable", myConnectionString);
//fill the dataset
adp.Fill(ds);
//do work in here to update rows, remove rows and anything like that
...
...
...
//now write back the changes with the adapter.
adp.Update(ds);
|
|
|
|
 |
|
 |
If one added identiy type GUID will it work?
It was late and I did not read the comments couple lines down.
Disregard.
|
|
|
|
 |
|
 |
I am using MS SQL 2005 and VBN 2005. I made the routine for VB Net , everything worked OK but the Table is loading the identity seed as False, even so is True in MS SQL. I solved the problem by loading the Schema in the Dataadapter but this is causing me problems with other routines because I am not using Typed Datasets. I am thinking in modifying the function to pass the name of the Id column too. Is there any other way to get the Identity seed (True/False) without loading the schema ?
Thanks
|
|
|
|
 |
|
 |
How would you insert an image into a field. Access has the memo field, FoxPro the blob field.
Can you write and Insert Into that contains a binary stream?
Thanks for your article.
|
|
|
|
 |
|
|
 |
|
 |
The reason why I was doing it this way, is because I am tabbing thru a DataGridView adding new entries, and at the end of a new row, I want to immediately add a new entry and get the identity because I then add other entries to other tables using the identity.
I am not sure if it is so easy with SqlCommandBuilder. My main problem was with DataSet Designer and the fact that I kept on losing my custom commands each time I changed the database.
|
|
|
|
 |
|
 |
It does that and its easy too. TheRefreshSchema does all that for you.
Abi ( Abishek Bellamkonda )
My Blog: http://abibaby.wordpress.com
=(:*
|
|
|
|
 |
|
 |
The problem with the SQLCommandBuilder is that it hits the database to retrieve schema. That is slower than just constructing the Query from the local dataset/datatable.
Sam
|
|
|
|
 |
|
 |
You should really look into the System.Text.StringBuilder class, once you start adding more then 3 strings you should use it instead.
public static string BuildAllFieldsSQL ( DataTable table )
{
StringBuilder sql = new StringBuilder();
bool bFirst = true;
foreach ( DataColumn column in table.Columns )
{
if ( bFirst )
bFirst = false;
else
sql.Append(", ");
sql.Append(column.ColumnName);
}
return sql.ToString();
}
For the other method the performance will be even better.
|
|
|
|
 |
|
 |
You could improve that even further by removing the unnecessary local variable (bFirst):
public static string BuildAllFieldsSQL ( DataTable table )
{
StringBuilder sql = new StringBuilder();
foreach ( DataColumn column in table.Columns )
{
if (sql.Length > 0)
{
sql.Append(", ");
}
sql.Append(column.ColumnName);
}
return sql.ToString();
}
Don't worry, nobody lives forever.
|
|
|
|
 |
|
 |
What is the reason for using'; SELECT CAST(scope_identity() AS int)' instead of '; SELECT @@IDENTITY' ? Your code would probably break if I use a Guid as primary key.
|
|
|
|
 |
|
 |
@@IDENTITY gives last identity of the last SQL Insert statement. Scope_Identity() gives the last identity of the last SQL Insert statement, in the current context (not including any triggers).
Conside the following senario, where u have a table T and it has a trigger that will insert a new record into table Q. When you execute "INSERT INTO T('abi Bellamkonda');". @@Identity will give you identity of Q, but Scope_Identity() function will give Identity of T.
Yes, his code will not work for guid/BigInt...
Abi ( Abishek Bellamkonda )
My Blog: http://abibaby.wordpress.com
=(:*
|
|
|
|
 |