Insert Records in SQL Server from Oracle C# - c#

I am working on winform application in C# where I have to import some 200,000 records from an Oracle view and dump into SQL Server table. I am not sure how to approach this problem whether i should use datatable to hold all these records and then store it in SQL server Or I have to use some DBlink which I am not familiar with.
Any suggestions/recommendations will be greatly appreciated. Thanks!

A lot of how you handle it depends on the data and how it is used.
If it is dynamic data that is often changing, then having a live link might be better, although there still may be a speed issue. Or if it changes some but not often, reloading it to SQL Server using an SSIS package might be a good option. If having two copies of the data is simpler (and it's data that doesn't change), then just doing a one-time copy over might be acceptable.
Setting up a DB Link is not too hard and recommended if you're going to make a SSIS package or accessing the data through SQL Server but leaving it in Oracle.
If you're using the data and getting it fresh each month, and not modifying it in SQL, then creating a SSIS task and a DB Link would be a reasonable solution. Create the link and make sure it connects, then use SSIS to truncate your SQL table and then reload it from Oracle. Run the package during a time the application is not using the SQL copy of the data. Make a job to run the package. It might be reasonable to make a backup of the table before truncating, or copying to a temporary location, or some sort of process to recover in the case of a problem loading the data. Something like the following:
Job
step 1 Backup table
step 2 (if step 1 successful) Run SSIS package
Truncate table
Reload table using DB Link
step 3 (if step 2 failure) restore from backup

Open 2 connections. Read from one and write to the other. There is an Oracle .Net driver. It's called ODP.NET.

Related

Automatically manage Sql Server database size

There are 2 .NET services which use 2 SQL Server databases. I am currently using SQL Express so the maximum database size is an issue.
When the size approaches the 10GB limit (or some record limit), I would like to automatically delete the oldest X amount of records to free up some space.
This is not a production environment and I REALLY don't need the old data, I just want to keep the data "fresh".
Should this be done at the service level? I can modify my services to periodically check spaceused and execute a manual "clean up" (Whether it's a delete, archive, etc.). I'm not sure how do this on the SQL level however.
Since you are using SQL Express, you will need to do this at the service level on some schedule. You will first need to delete the rows out of the table(s) that you want to purge the data from. Something like:
delete BigOleTable where LoggedDate < dateadd(yy,-1,getdate())
that will get rid of stuff older than a year.
Then, you will need to shrink the database.. so, this depends on your recovery model. If you're in full recovery, you'll need to backup the transaction log. and then issue a shrinkdatabase as Tanner alluded to above.
You can create a job that does this or better use SSIS (see this: http://technet.microsoft.com/en-us/library/ms181153%28v=sql.105%29.aspx).
You can use this http://technet.microsoft.com/en-us/library/ms188776.aspx procedure to query the space used and if it exceeds a thesshold you could delete data.

SQL Server data import dilemma

I have created an application that will be importing CSV files into a database table, and I've got multiple CSV files I need to import into a table in a SQL Server database.
I've got a couple approaches in mind but I'm not sure which is most practical. The application works by asking the user to select the files they want to import (from their local file system) and then they simply click a [Load Files] button. These files may contain 100,000+ rows at times.
What would be better for the above scenario?
Import CSV file into datatable using C# and open-source GenericParser then using a traditional method of BulkCopy to push the datatable to the database
Note: my concern is the strain on users PC when doing this for files with 100,000+ rows. How will this affect the processing or would it crash the program?
Use Bulk Insert which requires the file name and path. My concern for this option is I'm not sure if the server would be able to process the Bulk Insert command without the physical file being located on the server? The file path would relate to the users local machine. The only time I've used Bulk Insert is when I was logged onto the server itself, which is not possible for this app.
Is there a way to do it with Linq? While I'm not really familiar with Linq if it can be accomplished I'm open to trying it.
Any insight is appreciated. I know what I need to do just not sure of how to accomplish it practically.
Thanks
My recommendation would be to use the SqlBulkCopy class in .NET. It will allow you to import rows almost as fast at the BULK INSERT statement, but only requires that you populate a DataTable with the rows, and then send them to SQL Server.
Another consideration you might want to look at would be (and this is my personal favorite for simple file import programs) to use PowerShell instead of C#, which has a built-in cmdlet for imporing CSV files. Pretty cool stuff.
1) loader app in .Net is a good choice, generally. 100,000 rows is really not a strenuous workload, especially for simple loads. Only if there is a ton of multiple-table-joins involved in order to look up values on the fly would that really be a big concern.
2) although strictly speaking physical file location is just a performance question, I wouldn't do it. It will introduce administrative headaches.
3) I don't have experience with Linq, I cannot remark.
Just for bonus alternate idea: if you have IIS running somewhere, maybe even on the DB server, you can whip up a lightweight, one-page "webapp" which is just a CGI script with ODBC connection to the DB and the user just feeds the CSV in as a "web/CGI" upload. No utility application to install on user workstations this way.
To solve your problem, you have to see on in two basic views:
Do you need make some operations with data before insert in into database (some sumarization, correction,...)?
If yes, than here is the best way to upload rows from file to object (each row into one object instance). And than you can elegantly move with list of items with Linq.
Do you need only insert rows from file to database as they are?
I this case, use process described in point 2 of your question.
I'd prefer to upload file to server before any action. It's more safe.

Copy data from SQL Server to Mysql

I have a MS SQL database, that i want to copy to a mysql database,
its a very large database, with a table having about 2 million rows,
Currenlty i am copying it using code in C#, that uses datareader to loop through all rows in SQL table and inserts in a mysql table, but this is taking very long time, is there any other alternative to copy database, ?
both databases mysql and ms sql have same tables structure.
Please advice,
Thanks
Depending on the SQL Server edition you have available, you can use Integration Services, that handles the reading from SQL Server, type conversions, and writing to the target MySQL. It's optimized to do it as quickly as possible.
And it's not too hard to learn to use it.
You simply have to create a package, with a source (SQL Server), a destination (MySQL) and the extra components that you can find useful (probably only Change Type).
You can use the
MySql migration Toolkit
or
MSSQL2MySQL
Haven't used either personally but they are a couple of the toolkits available.
Much like the other answer, there are a number of ways you could go about doing this. The first thing that popped into my head was using SSIS to migrate the data.
http://www.packtpub.com/article/mysql-data-transfer-using-sql-server-integration-services-ssis
You could also look into Talend Open Studio. I use TOS to migrate data from several databases, including MS SQL, to a MySQL database. Its easy to learn and easy to maintain.
I dunno if you are willing to pay for that(I think you should in such scenario) I would recommend using DBSync for MS SQL & MySQL.
I had the task to migrate a huge 25Gb database from SQL Server to MySQL and this little program (only 17Mb compared to 277Mb Talend Open Studio ) works fine.
It s deadly simple to use , simply follow the steps (5 steps) and you go your database migrated.
I have tried Talend Open Studio and the documentation is not good at all and there is a long learning curve there whereas with DBSync, if you ever installed a software on you PC then you can also do it very easily.
Also if you one of those who like testing before buying, you can try the free version which can at least migrate the 50 first rows of all tables in a database.
I would defiantly give is a go and if you are dealing with a huge amount of sensible data,$99 is a treat. if you find any simpler or faster way to do it please let us know cause I often migrate databases and I would appreciate if you d have any better.

Upload a Massive CSV File to SQL Server Database

I need to upload a massive (16GB, 65+ million records) CSV file to a single table in a SQL server 2005 database. Does anyone have any pointers on the best way to do this?
Details
I am currently using a C# console application (.NET framework 2.0) to split the import file into files of 50000 records, then process each file. I upload the records into the database from the console application using the SqlBulkCopy class in batches of 5000. To split the files takes approximately 30 minutes, and to upload the entire data set (65+ million records) takes approximately 4.5 hours. The generated file size and the batch upload size are both configuration settings, and I am investigating increasing the value of both to improve performance. To run the application, we use a quad core server with 16GB RAM. This server is also the database server.
Update
Given the answers so far, please note that prior to the import:
The database table is truncated, and all indexes and constraints are dropped.
The database is shrunk, and disk space reclaimed.
After the import has completed:
The indexes are recreated
If you can suggest any different approaches, or ways we can improve the existing import application, I would appreciate it. Thanks.
Related Question
The following question may be of use to others dealing with this problem:
Potential Pitfalls of inserting millions of records into SQL Server 2005 from flat file
Solution
I have investigated the affect of altering batch size, and the size of the split files, and found that batches of 500 records, and split files of 200,000 records work best for my application. Use of the SqlBulkCopyOptions.TableLock also helped. See the answer to this question for further details.
I also looked at using a SSIS DTS package, and a BULK INSERT SQL script. The SSIS package appeared quicker, but did not offer me the ability to record invalid records, etc. The BULK INSERT SQL script whilst slower than the SSIS package, was considerably faster than the C# application. It did allow me to record errors, etc, and for this reason, I am accepting the BULK INSERT answer from ConcernedOfTunbridgeWells as the solution. I'm aware that this may not be the best answer for everyone facing this issue, but it answers my immediate problem.
Thanks to everyone who replied.
Regards, MagicAndi
BULK INSERT is run from the DBMS itself, reading files described by a bcp control file from a directory on the server (or mounted on it). Write an application that splits the file into smaller chunks, places them in an appropriate directory executes a wrapper that executes a series of BULK INSERTS. You can run several threads in parallel if necessary.
This is probably about as fast as a bulk load gets. Also, if there's a suitable partitioning key available in the bulk load file, put the staging table on a partition scheme.
Also, if you're bulk loading into a table with a clustered index, make sure the data is sorted in the same order as the index. Merge sort is your friend for large data sets.
Have you tried SSIS (SQL Server Integration Services).
The SqlBulkCopy class that you're already using is going to be your best bet. The best you can do from here in your c# code is experiment with your particular system and data to see what batch sizes work best. But you're already doing that.
Going beyond the client code, there might be some things you can do with the server to make the import run more efficiently:
Try setting the table and database size before starting the import to something large enough to hold the entire set. You don't want to rely on auto-grow in the middle of this.
Depending on how the data is sorted and any indexes one the table, you might do a little a better to drop any indexes that don't match the order in which the records are imported, and then recreate them after the import.
Finally, it's tempting to try running this in parallel, with a few threads doing bulk inserts at one time. However, the biggest bottleneck is almost certainly disk performance. Anything you can do to the physical server to improve that (new disks, san, etc) will help much more.
You may be able to save the step of splitting the files as follows:
Instantiate an IDataReader to read the values from the input CSV file. There are several ways to do this: the easiest is probably to use the Microsoft OleDb Jet driver. Google for this if you need more info - e.g. there's some info in this StackOverflow question.
An alternative method is to use a technique like that used by www.csvreader.com.
Instantiate a SqlBulkCopy object, set the BatchSize and BulkCopyTimeout properties to appropriate values.
Pass the IDataReader to SqlBulkCopy.WriteToServer method.
I've used this technique successfully with large files, but not as large as yours.
See this and this blog posts for a comparison.
It seems the best alternative is to use BulkInsert with the TABLOCK option set to true.
Have you tried using the Bulk Insert method in Sql Server?
Lately, I had to upload/import a lot of stuff, too (built a PHP script).
I decided to process them record-for-record.
Of course, it takes longer, but for me, the following points were important:
- easily pause the process
- better debugging
This is just a tip.
regards,
Benedikt
BULK INSERT is probably already the fastest way. You can gain additional performance by dropping indexes and constraints while inserting and reestablishing them later. The highest performance impact comes from clustered indexes.
Have you tried SQL Server Integration Services for this? It might be better able to handle such a large text file
Just to check, your inserting will be faster if there are no indexes on the table you are inserting into.
My scenario for things like that is:
Create SSIS Package on SQL server which using BLUK insert into sql,
Create stored procedure inside the DataBase to can run that Package from T-SQL code
After that send file for bluk insert to SQL server using FTP and call SSIS Package usinfg stored procedure

What are the pitfalls of inserting millions of records into SQL Server from flat file?

I am about to start on a journey writing a windows forms application that will open a txt file that is pipe delimited and about 230 mb in size. This app will then insert this data into a sql server 2005 database (obviously this needs to happen swiftly). I am using c# 3.0 and .net 3.5 for this project.
I am not asking for the app, just some communal advise here and potential pitfalls advise. From the site I have gathered that SQL bulk copy is a prerequisite, is there anything I should think about (I think that just opening the txt file with a forms app will be a large endeavor; maybe break it into blob data?).
Thank you, and I will edit the question for clarity if anyone needs it.
Do you have to write a winforms app? It might be much easier and faster to use SSIS. There are some built-in tasks available especially Bulk Insert task.
Also, worth checking Flat File Bulk Import methods speed comparison in SQL Server 2005.
Update: If you are new to SSIS, check out some of these sites to get you on fast track. 1) SSIS Control Flow Basics 2) Getting Started with SQL Server Integration Services
This is another How to: on importing Excel file into SQL 2005.
This is going to be a streaming endeavor.
If you can, do not use transactions here. The transactional cost will simply be too great.
So what you're going to do is read the file a line at a time and insert it in a line at a time. You should dump failed inserts into another file that you can diagnose later and see where they failed.
At first I would go ahead and try a bulk insert of a couple of hundred rows just to see that the streaming is working properly and then you can open up all you want.
You could try using SqlBulkCopy. It lets you pull from "any data source".
Just as a side note, it's sometimes faster to drop the indices of your table and recreate them after the bulk insert operation.
You might consider switching from full recovery to bulk-logged. This will help to keep your backups a reasonable size.
I totally recommend SSIS, you can read in millions of records and clean them up along the way in relatively little time.
You will need to set aside some time to get to grips with SSIS, but it should pay off. There are a few other threads here on SO which will probably be useful:
What's the fastest way to bulk insert a lot of data in SQL Server (C# client)
What are the recommended learning material for SSIS?
You can also create a package from C#. I have a C# program which reads a 3GL "master file" from a legacy system (parses into an object model using an API I have for a related project), takes a package template and modifies it to generate a package for the ETL.
The size of data you're talking about actually isn't that gigantic. I don't know what your efficiency concerns are, but if you can wait a few hours for it to insert, you might be surprised at how easy this would be to accomplish with a really naive technique of just INSERTing each row one at a time. Batching together a thousand or so rows at a time and submitting them to SQL server may make it quite a bit faster as well.
Just a suggestion that could save you some serious programming time, if you don't need it to be as fast as conceivable. Depending on how often this import has to run, saving a few days of programming time could easily be worth it in exchange for waiting a few hours while it runs.
You could use SSIS for the read & insert, but call it as a package from your WinForms app. Then you could pass in things like source, destination, connection strings etc as parameter/configurations.
HowTo: http://msdn.microsoft.com/en-us/library/aa337077.aspx
You can set up transforms and error handling inside SSIS and even create logical branching based on input parameters.
If the column format of the file matches the target table where the data needs to end up, I prefer using the command line utility bcp to load the data file. It's blazingly fast and you can specify and error file for any "odd" records that fail to be inserted.
Your app could kick off the command if you need to store the command line parameters for it (server, database, username / password or trusted connection, table, error file etc.).
I like this method better than running a BULK INSERT SQL command because the data file isn't required to be on a system accessible by the database server. To use bulk insert you have to specify the path to the data file to load, so it must be a path visible and readable by the system user on the database server that is running the load. Too much hassle for me usually. :-)

Categories

Resources