SQLBulkCopy Vs. Batch Update

Apr 17, 2007

I have a collection of around 16000 records, and have been trying to find the best way to update the information in the DB. I have done alot of reading about both BulkCopy and Batch Update, but haven't come to any clear solutions as to which performs better. I am not doing any inserting, just getting a dataset from the DB, changing the values, them want to update the Db again.

Thanks for any help.
 
Mick 

View 8 Replies


ADVERTISEMENT

Batch Update

Aug 12, 2007

Hai, i would like to do Bulk update to avoid the round trip to the database.
Means, In my UI im dsiplaying all the employee details who are related to one particular dept. Now i want to update the bonus to all the employees based on their category. UI changes are refelected in the Datatable(.NET). Finally the datatable changes i would like to update in the Database.
how can i do that..
sample code pls.
im very very new to sql

View 3 Replies View Related

Batch Update Of A SQL Table

Jul 1, 2007

Can anyone help a beginner with some T-SQL which runs as a scheduled stored procedure to update a table with is then accessed via an ASP web application.
 I have a table called Loans which contains a calculated column which will indicate in days if a loan item is late and also each row has a charges column to reflect a charge for late returns.
In a seperate table I have a charge per day for late returns.  I read this into a variable @LateCharges
I'd like to consutruct some T-SQL to scan through the Loans table and for every row where Status is not 'Returned' I woule like it to update the charges column based on the DaysLate column*@Latecharges
Any help much appreciated.
Regards
Clive

View 3 Replies View Related

Use Batch File To Update SQL

Apr 15, 2004

Ok.. I thought I could do this but I can't get this to work.. I need to create a batch file to run an sql update statement.. This is simple but I can't get it to wortk.. How do I do it?

View 4 Replies View Related

Batch Update In Stored Procedure

Feb 26, 2004

The following code is a part of my stored procedure MySP. I would like to update Users table with input variable @userIDs which has the following format:

101, 102, 103

I got the error message:

Syntax error converting the varchar value '101, 102, 103' to a column of data type int.

Obviously, UserID has datatype int. How can I write this SP?


CREATE PROCEDURE dbo.MySP
@userIDs varchar(100)
AS
SET NOCOUNT ON

BEGIN TRANSACTION

UPDATE Users SET IsActive = 1 WHERE UserID IN (@userIDs)

IF @@ERROR <> 0
ROLLBACK TRANSACTION
ELSE
COMMIT TRANSACTION

SET NOCOUNT OFF

View 8 Replies View Related

Strange Exception - Batch Update

Apr 19, 2007

Can anyone help me understand what this means:




Code Snippet

java.sql.BatchUpdateException: com.microsoft.sqlserver.jdbc.SQLServerException: The IOBuffer.process operation returned an unknown packet type:0. Index:41. End:83.TDS_DONEINPROC(-1) TDS_DONEPROC(-2) TDS_DONE(-3) TDS_COLMETADATA(-127)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeBatch(Unknown Source)




I'm trying to do a very simple batch update.

View 7 Replies View Related

Checking For Unique Constraints During A Batch Update

Jan 28, 2004

hello .
i have a grid for a table that gets updated with recordset.updatebatch
for a multi-user application.

the problem is that some of the table fields have to be unique

now imagine the next situation.

user A opens the form
user B opens the form
user A writes '1000' in the unique field
user A saves the recordset with updatebatch

user B writes '1000' in the unique field
user B saves the recordset with updatebatch

now there will be two records with the field '1000' !

how can i avoid this ?
i cannot check for unique during the update event of the grid
because it should check during the time it is saving and not
when it is just entering data without having updated the recordset

thanks !

View 2 Replies View Related

Database Change In Batch Update SQL Script

Oct 31, 2007

I used "OLE DB Command"(row by row) for update but because i found that very very slow i decided to try batch update. I check what is for insert and what is for update and those things that are for update i save to temp table. Then i run this:
update [ODS].[dbo].[Adres]
SET
[MutatieDatumEinde] = stAdres.MutatieDatumEinde,
[StraatNaam] = stAdres.StraatNaam,
[HuisNummer] = stAdres.HuisNummer,
[HuisNummerToevoeging] = stAdres.HuisNummerToevoeging,
[Postkode] = stAdres.Postkode,
[Plaats] = stAdres.Plaats,
[Land] = stAdres.Land,
[IndicatiePTTAdresStandaard] = stAdres.IndicatiePTTAdresStandaard,
[KodeHerkomstAdres] = stAdres.KodeHerkomstAdres,
[VervalDatum] = stAdres.VervalDatum,
[BronODS] = stAdres.BronODS
from
[ODS].[dbo].[Adres] oAdres
inner join [M2O_Stage].[dbo].[ODS_Adres] stAdres
on oAdres.InstNr = stAdres.InstNr and
oAdres.TypeAdres = stAdres.TypeAdres and
oAdres.MutatieDatumAanvang = stAdres.MutatieDatumAanvang
where stAdres.IsInsert = '0'


I run this as an "execute sql task". Everything is running as it should and speed is incomparable, but.. i have problem to make this generic... what i mean is.. db names will change.
How can i make db names dynamic here ?

p.s. i just got idea .. i could probably make dynamic sql statement in script component and then run it there... but does anyone have a better idea ?

View 3 Replies View Related

Create Batch File That Will Run Update Statement And Schedule It To Run?

Oct 7, 2013

Is there a way to create a Batch file that will run an Update Statement and schedule it to run?I've used bcp to extract data to a txt file before, but i'm not sure if an Update can be performed.I'm using SQL Server 2008 R2 Express Edition so i don't have Server Agent available.

View 7 Replies View Related

Batch Script To Create ODBC And Update Registry Datasource Key - Help!

Feb 21, 2008



I have create a batch file, that creates an ODBC then updates the application datasource key in the registry to the new system dsn name.

The problem is that the new DSN doesn't work when i try and connect the application...but if i had manually created the odbc source the app connects as expected... i have checked the registry and there is no difference between the two dsns created...but the application throws IM002[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified after i have also changed the applications registry key to point to the new database.

Now the interesting things to note are that when i re-create the odbc to the old server and database (sql 2000) by batch file it works fine. The new ODBC is linking to a sql 2005 database, but it is still using the 2000 drivers and when i manually created it, it worked also.

Another interesting thing is that if i go into the odbc dsn and click configure, go through and test the connection it works fine... after i close this i then retry the application and it opens correctly...

I need this to be automated with no manual intervention, as this will be added to a large group of users login scripts!

Any help greatly appreciated.

My batch file code is as below:

ODBCCONF.exe CONFIGSYSDSN "SQL Server" "DSN=RMS Live 2005 | SERVER=d-db99sql2005| Trusted_Connection=Yes | Database=RMS-Livedb"

View 4 Replies View Related

Passing Parameters To Batch File And Executing Batch File Loop

Aug 7, 2007

HELP,

I need to take a variable from a tabel in SQL Server pass to a Batch file and execute the batch file. Right now I can exec the batch file with XP_CMDSHELL but how can I pass the variable to the batch file and loop through all the variables.

Please help

Phil

View 4 Replies View Related

SQLBULKCOPy

May 23, 2007

I am using SQLBULKCOPY to copy Excel spreadsheet into SQL Express Database table.  The copying went okay, but the only problem I have is that few records in one of the columns is NULL. 
The column contains numeric and alphnumeric fields in the spreadsheet.  After copying, the numeric fields got copy with no complication, but all the alphanumeric fields all becam NULL.  Can someone help me with this problem?

View 4 Replies View Related

SQLBulkCopy In LAN

Jun 9, 2008

HI,
I have one doubt. Is it possible to transfer data from one SQL Server to other SQL Server over the LAN.( Both the SQL Server database are in different cities)

View 1 Replies View Related

SqlBulkCopy

May 19, 2005

Hello,
I was curious if anyone knew if using SqlBulkCopy in code required any special permissions on the database side.  I wasn't sure if more permissions than writing capabilities were needed.
Thanks.

View 1 Replies View Related

Question On Using SQLBulkCopy

Feb 4, 2007

I need to copy large amounts of data between SQL databases, and between SQL and Access.  I've been reading a lot of good explanations of SQLBulkCopy, but the only good examples I've found are written in C# and I work in VB.  I'm very new to ASP.NET 2.0 (about a month) and came from Classic ASP, not .NET 1.1.  I'm still getting my feet wet and I'm afraid it doesn't take much to confuse me.  Can someone point me to a good article or tutorial that includes a clear example written in VB?
Diane

View 1 Replies View Related

SQLBulkCopy Question

Nov 28, 2007

Hi,
I am trying to use sqlbulkcopy to insert the contents of a data table to a temporary table in the database. The content of data table comes from a csv file. I can add the rows to the data table but it seems they are added as strings and when I try to WriteToServer(datatable) it chokes becuase my table has some int fields. Not sure how to do this.private static TimeSpan DoBulkCopy(string filePath)
{Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
StreamReader sr = new StreamReader(filePath);
prepareTable();string fullFileStr = sr.ReadToEnd();
sr.Close();
sr.Dispose(); string[] lines = fullFileStr.Split('');
DataTable dt=new DataTable() ;string[] sArr =lines[0].Split(',');foreach(string s in sArr)
{dt.Columns.Add(new DataColumn());
}
DataRow row;string finalLine = "";foreach (string line in lines)
{
row = dt.NewRow();finalLine = line.Replace(Convert.ToString('
'), "");row.ItemArray = finalLine.Split(',');
dt.Rows.Add(row);
} SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["connectionString"].ToString());System.Data.SqlClient.SqlBulkCopy bc = new System.Data.SqlClient.SqlBulkCopy(cn, SqlBulkCopyOptions.TableLock, null);
bc.BatchSize = dt.Rows.Count;
cn.Open();bc.DestinationTableName = "tmpTable";
bc.WriteToServer(dt);   // <---------------   it dies here
cn.Close();
bc.Close(); TimeSpan ts = stopWatch.Elapsed;
stopWatch.Stop();return ts;
}private static void prepareTable()
{SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["connectionString"].ToString());
string sql = @"if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tmpTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)drop table [dbo].[tmpTable]; CREATE TABLE [dbo].[tmpTable] ([Remote] [int],[KFP] [int]) ON [PRIMARY]";SqlCommand cmd = new SqlCommand(sql, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
cmd.Dispose();
}

View 1 Replies View Related

Question About SqlBulkCopy

Feb 29, 2008

Hello.

I have a problem using SqlBulkCopy for updating tables. In fact, I can´t update any table. I use this function for insert big groups of records, but I would like to know how I can configure SqlBulkCopy for update rows. I would like to see if there is a record (primary key exists) then update it.

Is possible?

Greetings.

Tanen.

View 1 Replies View Related

SqlBulkCopy And Indexes

Apr 25, 2008

Does SqlBulkCopy have any adverse affects on it's target table indexes? I like the performance gain but am worried about creating unnecessary table scans if the indexes/stats are not updated properly after it completes...

View 1 Replies View Related

SqlBulkCopy Error Messages

Sep 6, 2006

I'm using SqlBulkCopy.  Does anyone know how I can output what row (its column names) are throwing a duplicate primary key message when I bulkCopy.WriteToServer(datatable1)?Thanks 

View 1 Replies View Related

Timeout Using SqlBulkCopy Across Servers

Apr 27, 2007

I'm in the final throws of redesigning a web application, and one of the major improvements is adding in an admin page for the users so they can maintain the data and system structure without the need for us to get involved.
One of the areas I'd held back on was promotion of data from SQL server to SQL server - once .NET 2 framework came in and we moved over to VS2005, I'm now in a position to do this work. 
I have tested it and it works perfectly well for small tables, but as soon as I try it on a reasonably large table (860,000 rows) I get the following error in VS's output window:
"A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."
The application data is stored on SQL2005 servers, and I am running the application locally.  I have tried running the copy from table to table on the same server (different databases) and i get the same result, which leads me to believe that it may be memory related.  Running the SQL in SQL Server Management Studio works in just 15 to 20 seconds, but using VS falls over in just under a minute.  My connection string has a timeout of 3600.
Here's my C# code:// Execute reader...
using (IDataReader vReader = vCmd.ExecuteReader())
{
// Create SqlBulkCopy...
SqlBulkCopy vBulkData = new SqlBulkCopy(aTargetConn);
// Set destination table name...
vBulkData.DestinationTableName = aTableName;
// Write data...
vBulkData.WriteToServer(vReader);
}

aSourceConn and aTargetConn are the appropriate SqlConnections, and aTableName is the table to be populated with data (previously backed up and emtied of contents).
Any help/advice suggestions gratefully received - if any more info needed please ask.
Thanks
Martin
 

View 6 Replies View Related

Importing CSV Files With SqlBulkCopy

May 2, 2007

I am trying to import a CSV file into an SQL Server table with the OleDbDataReader and SqlBulkCopy objects, like this:   using (OleDbConnection dconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\mystuff\;Extended Properties="text;HDR=No;FMT=Delimited""))
{
using (OleDbCommand dcmd = new OleDbCommand("select * from mytable.csv", dconn))
{
try
{
dconn.Open();

using (OleDbDataReader dreader = dcmd.ExecuteReader())
{
try
{

using (SqlConnection dconn2 = new SqlConnection(@"data source=MyDBServer;initial catalog=MyDB;user id=mydbid;password=mydbpwd"))
{
using (SqlBulkCopy bc = new SqlBulkCopy(dconn2))
{
try
{
dconn2.Open();
bc.DestinationTableName = "dbo.mytable";
bc.WriteToServer(dreader);
}
finally
{
dconn2.Close();
}
}
}
}
finally
{
dreader.Close();
}

}
}
finally
{
dconn.Close();
}
}
}
A couple of the columns for the destination table use a bit datatype.  The CSV files uses the strings "1" and "0" to represent these.When I run this code, it throws this exception:Unhandled Exception: System.InvalidOperationException: The given value of type String from the data source cannot be converted to type bit of the specified target column. ---> System.FormatException: Failed to convert parameter value from a String to a Boolean. ---> System.FormatException: String was not recognized asa valid Boolean.   at System.Boolean.Parse(String value)   at System.String.System.IConvertible.ToBoolean(IFormatProvider provider)   at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)   at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType)   --- End of inner exception stack trace ---   at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType)   at System.Data.SqlClient.SqlBulkCopy.ConvertValue(Object value, _SqlMetaDatametadata)   --- End of inner exception stack trace ---   at System.Data.SqlClient.SqlBulkCopy.ConvertValue(Object value, _SqlMetaDatametadata)   at System.Data.SqlClient.SqlBulkCopy.WriteToServerInternal()   at System.Data.SqlClient.SqlBulkCopy.WriteRowSourceToServer(Int32 columnCount)   at System.Data.SqlClient.SqlBulkCopy.WriteToServer(IDataReader reader)   at MyClass.Main()It appears not to accept "1" and "0" as valid strings to convert to booleans.  The System.Convert.ToBoolean method appears to work the same way. Is there any way to change this behavior?  I discovered if you change the "1" to "true" and "0" to "false" in the  CSV file it will accept them.  

View 3 Replies View Related

SQLBulkCopy Issues With ODBC

Jun 15, 2007

I am trying to use SQLBulkCopy to copy from an excel spreadsheet to a table in a SQL database and it is all working fine, but I have to now change the connection to the SQl database to an ODBC connection and it is now erroring.
This is the error I get - keyword not supported 'dsn'
Is it possible to use SQlBulkCopy when using an odbc connection to the SQL database?

View 2 Replies View Related

I Can't Make SqlBulkCopy Work

Feb 7, 2008

I have a scenario whereby I'd like to insert multiple rows into a table on a SQL server database as efficiently and easily as possible.
After some research, it looked like .NET 3.0's SqlBulkCopy class would do what I want. I've tried to set something up, but it's not working. It's not even throwing an error. The code executes but it simply hasn't done the insert by the end of it!
 My table structure is simple. The name of the table is LPSTUnavailableDate. It has just two columns, one of them an auto-populated ID field:


LPSTUnavailableDateId, INT, PRIMARY KEY, IDENTITY(1,1)

View 1 Replies View Related

Mysterious Error With SQLBulkCopy

Jun 5, 2008

I have encountered a very frustrating situation when trying to use SQLBulkCopy. I have two excel files that I am trying to import into two tables in an MSSQL Server 2005 Express DB. One excel file has 5,000 rows, while the other file has 500,000 rows.I was able to import the smaller file successfully using this vb.net code:  Protected Sub L26ExcelToSQL() 'Declare Variables
Dim sSQLTable As String = "Local26Members"
Dim sExcelFileName As String = "Full Local 26 List Formatted.xls"
Dim sWorkbook As String = "[Sheet1$]"

'Create connection strings
Dim sExcelConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=D:hostingmemberwolsite1l26voterreg" & sExcelFileName & ";" & _ "Extended Properties=""Excel 8.0;HDR=YES"""



Dim sSqlConnectionString As String = ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString.ToString 'Execute a query to erase any previous data from our destination table
Dim sClearSQL = "DELETE FROM " & sSQLTable Dim SqlConn As SqlConnection = New SqlConnection(sSqlConnectionString) Dim SqlCmd As SqlCommand = New SqlCommand(sClearSQL, SqlConn) SqlConn.Open() SqlCmd.ExecuteNonQuery() SqlConn.Close() 'Series of commands to bulk copy data from the excel file into our SQL table
Dim OleDbConn As OleDbConnection = New OleDbConnection(sExcelConnectionString) Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM " & sWorkbook), OleDbConn) OleDbConn.Open() Dim dr As OleDbDataReader = OleDbCmd.ExecuteReader() Dim bulkCopy As SqlBulkCopy = New SqlBulkCopy(sSqlConnectionString) bulkCopy.DestinationTableName = sSQLTable bulkCopy.WriteToServer(dr) OleDbConn.Close() End Sub
  However, when I tried to import the 500,000 row excel file, I got the following error: Server Error in '/L26' Application.

A
transport-level error has occurred when receiving results from the
server. (provider: TCP Provider, error: 0 - The specified network name
is no longer available.)



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:
A transport-level error has occurred when receiving results from the
server. (provider: TCP Provider, error: 0 - The specified network name
is no longer available.)

Source Error:




Line 438:Line 439: bulkCopy.DestinationTableName = sSQLTableLine 440: bulkCopy.WriteToServer(dr)Line 441:Line 442: OleDbConn.Close()







Source File: d:hostingmemberwolsite1L26DuesDefault2.aspx.vb    Line: 440


Stack Trace:




[SqlException (0x80131904): A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The specified network name is no longer available.)] System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +925466 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +800118 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +186 System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error) +556 System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult asyncResult, TdsParserStateObject stateObj) +164 System.Data.SqlClient.TdsParserStateObject.ReadPacket(Int32 bytesExpected) +34 System.Data.SqlClient.TdsParserStateObject.ReadBuffer() +44 System.Data.SqlClient.TdsParserStateObject.ReadByte() +17 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +79 System.Data.SqlClient.SqlBulkCopy.WriteToServerInternal() +1336 System.Data.SqlClient.SqlBulkCopy.WriteRowSourceToServer(Int32 columnCount) +916 System.Data.SqlClient.SqlBulkCopy.WriteToServer(IDataReader reader) +151 _Default.CSVToSQL() in d:hostingmemberwolsite1L26DuesDefault2.aspx.vb:440 _Default.ButtonTest3_Click(Object sender, EventArgs e) in d:hostingmemberwolsite1L26DuesDefault2.aspx.vb:905 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746









Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433 After I received this error message, I tried viewing my database through the MSSQL Control Panel utilized by my hosting provider (WebHost4Life). However, I was unable to connect to the database and received this error: ___________________Microsoft OLE DB Provider for SQL Server error '80040e14' Database 1496 cannot be autostarted during server shutdown or startup. /getDBinfo.asp, line 29

_____________________ Now here is the most frustrating/mysterious part. I figured that maybe the error message were a result of the large size of the second excel file, so just for testing purposes, I created a new table in my MSSQL database. The table just has two fields, both set to varchar(50). I then created a test excel file, that had one row with the word "test" in the first and second column. When I tried using the code above to import the test excel data into the test table, I got the same exact error as I did with the 500,000 row file!Please help, I'm really stumped and I am not sure when I am having so much trouble replicating the success I had the 5,000 row file. Any suggestions are much apprecaited. -Bryan  

View 4 Replies View Related

SqlBulkCopy And Context Connection = T

Oct 6, 2006

I have created an assembly which I load into SQL 2005. However, if I set my connection string = context connection = true... I will get an error saying something like this feature could not be used in this context... So I changed my function to insert each row.... Now the issue I have is the transfer takes 4X as long.... Before I made the change I was using the bulkcopy by specifying the actual connection string....but I also had to specify the password in the string...and since I wanted to get way from this specification...I attempted the context route. So...is there any other way of using the bulkcopy feature or something like it using the context connection?

Private Shared Function BulkDataTransfer2(ByVal _tblName As String, ByRef _dt As DataTable, ByRef emailLog As String) As Boolean

Dim success As Boolean = False

emailLog = emailLog & System.DateTime.Now.ToString & " - bulk transfer2 - " & _tblName & vbCrLf

Dim insertStr As String = "INSERT INTO " & _tblName & "("

Dim values As String = ") Values("

Dim drow As DataRow = Nothing

Dim dCol As DataColumn = Nothing

'add the column names

For Each dCol In _dt.Columns

insertStr = insertStr & dCol.ColumnName.ToString & ", "

values = values & "@" & dCol.ColumnName.ToString & ", "

Next

'remove the last comma & form the final string

insertStr = insertStr.Substring(0, insertStr.Length - 2)

values = values.Substring(0, values.Length - 2)

insertStr = insertStr & values & ")"



Dim connStr As String = "context connection = true"

Dim conn As New SqlConnection(connStr)

Dim cmd As SqlCommand = Nothing



Using conn

Try

conn.Open()

For Each drow In _dt.Rows

cmd = New SqlCommand(insertStr, conn)

For Each dCol In _dt.Columns

cmd.Parameters.AddWithValue("@" & dCol.ColumnName.ToString, drow.Item(dCol.ColumnName.ToString))

Next

SqlContext.Pipe.ExecuteAndSend(cmd)

Next

success = True

Catch ex As Exception

emailLog = emailLog & System.DateTime.Now.ToString & " " & ex.ToString & vbCrLf

success = False

Finally

Try

conn.Close()

conn.Dispose()

Catch ex As Exception

success = False

End Try

End Try

End Using

Return success

End Function



View 4 Replies View Related

JDBC Equivalent Of SqlBulkCopy

Apr 20, 2008



Hi,

Is there a JDBC equivalent of the SqlBulkCopy command?

Simply using batched INSERTs, it takes days to insert 1m rows into SQL Server. However using C# client that uses SqlBulkCopy I can load it in about 1 hour.

Thanks in advance,
G.

View 5 Replies View Related

SqlBulkCopy CodePage Translation Vs BCP

Apr 24, 2007

I have deveoped a replacement for some an old bcp based applications in the .Net Framework that uses the SqlBulkCopy class.

I have run into some difficulties with code page translation:

The original BCP client runs with OEM Codepage 437 , thus the data "ëÄÆòÖ" gets loaded as "d-¦=+". DB is SQL_Latin1_General_CP1_CI_AS, column is varchar.

I have been unable to perform any code page Encoding in .Net that yields the same result.

I want to emulate this behaviour in my database loader but as yet have been able to find a way....

Any Ideas???

Thanks,
Niall

View 7 Replies View Related

SqlBulkCopy And Field Collation

Nov 19, 2007

I have the following table:
create table tTest
(
x varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS
)

I need to populate this table using SqlBulkCopy, however some symbols are inserted with mistakes.

Here is an example of the code that I€™m using:
using (SqlBulkCopy copier = new SqlBulkCopy(ci.ConnectionString))
{
copier.DestinationTableName = "tTest";
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("x"));

tbl.Rows.Add(new object[] { "u00fc" }); //letter ü

copier.WriteToServer(tbl);
}

At the same time DTS and the statement
insert tTest values(N'ü')

works correctly.

View 5 Replies View Related

SqlBulkCopy Issues With Duplicate Records

Sep 14, 2006

SqlBulkCopy does not seem to have much flexibility. If your table has columns that dont allow duplicates, you are apparently screwed.  Its a shame there is no switch or param setting you can issue the SqlBulkCopy class (if there is, please let me know!!)Example:Say I have a table "Cars" with fields "CarId" (identity) and "CarName" (varchar) and the CarName field has a unique constraint. Now, I have a DataTable that contains a bunch of CarNames to insert.  If there are duplicates on CarName, the entire insert fails.  This is nothing to do with the PK or identity field. The problem I have: I would much rather have an option to ignore or silently not insert that duplicate row, but continue to insert the rest of my data. Any known work arounds for this would be much appreciated.  Maybe I am missing something?

View 3 Replies View Related

SqlBulkCopy Login Failed Error

Mar 20, 2007

Hi There, I'm trying to use a sql bulk copy to transfer data from xml file to a table in one of my page.  In this page I'm doing 2 database related.  The first is a simple insert that will return a value and the second one is the sql bulk copy data transfer.  I'm using the same connection for both of them and the sql bulk copy always give me a "login failed" error while the insert is fine.  Do I need to set a specific setting for the sql server account so that it can use sql bulk copy? Thank you 

View 3 Replies View Related

Unexpected Existing Transaction With SqlBulkCopy

Oct 17, 2007

I have programmatically created a SqlConnection that begins a SqlTransaction.  During the first part of this SqlTransaction, the contents of a table are deleted.  The next part uses the SqlBulkCopy object to copy data from another database (in the form of a DataTable).  The delete goes through fine, but the SqlBulkCopy always generates a SqlException with the message "Unexpected existing transaction."  I cannot think of anything I am doing wrong. 
The code looks at an XML file for instructions on each transaction.  Each transaction is composed of tasks.  Each task will pull data from a different type of database (MVR.Command is a Factory Database object).  Please view the code below and tell me if you can spot what I am doing wrong:
 using (SqlConnection destinationConnection = new SqlConnection(MVR.ConnectionSource.GetConnectionString(destinationServiceName)))
{
destinationConnection.Open();

using (SqlTransaction transaction = destinationConnection.BeginTransaction(IsolationLevel.Snapshot, "Transport"))
{
transaction.Save("Beginning");

int totalTasks = 0;
int successfulTasks = 0;

foreach (XmlNode taskNode in transactionNode.SelectNodes("Tasks/Task"))
{
totalTasks += 1;

string sourceServiceName = taskNode.Attributes["sourceServiceName"].Value;
string destinationTablename = taskNode.Attributes["destinationTablename"].Value;
string query = taskNode.InnerText;

MVR.Command source = MVR.ConnectionSource.GetCommand(sourceServiceName);
source.CommandType = CommandType.Text;
source.CommandText = query;

DataTable sourceData = source.ExecuteDataTable();

try
{
// Prepare the destination table (delete everything)
int rowsDeleted = new SqlCommand("delete from " + destinationTablename, destinationConnection, transaction).ExecuteNonQuery();

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))
{
bulkCopy.DestinationTableName = destinationTablename;

bulkCopy.NotifyAfter = 1000;
bulkCopy.WriteToServer(sourceData);
bulkCopy.Close();

successfulTasks += 1;

// Log success
}
}
catch (Exception ex)
{
// Log failure
}
}

transaction.Save("End");

// Based on the success of all tasks, either commit or rollback
if (successfulTasks == totalTasks)
{
transaction.Commit();
}
else
{
transaction.Rollback();
}
}

destinationConnection.Close();

 

View 2 Replies View Related

Text File / SqlBulkCopy Code

Apr 29, 2006

Does anybody have the code to import a text file into a a Sql Server table using the SqlBulkCopy object?

View 1 Replies View Related

SQLBulkCopy In A C# App Causes SQL Server 2005 To Lock Up

May 16, 2007

I have written an app that will allow you to send a query to Teradata, return the results into a Reader and then Bulk Copy that data into SQL Server 2005.



If the query results in a large dataset (ie 20,000,000 rows) is processed then while that data is being bulk copied into SQL Server, using the SQLBulkCopy class, then it prevents users on other computers from logging into SQL Server Management Studio.

Those that are already logged in are shut down also. Everything appears fine to the users but queries do not finish running.



Everything immediatly starts working as normal when either my program finishes or I shut down my program.



Is there any type of property to the SQLBulkCopy class or any other function that will prevent Management Studio from locking up?



Thanks

Robert

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved