Showing posts with label records. Show all posts
Showing posts with label records. Show all posts

Thursday, March 29, 2012

Bulk Updates taking a long time

We have a huge table with around 25 Million records. We want to reset two int Columns of all records to 0. Currently its taking around 1.5 hours... What are the best practises we can follow to reduce the total update time.

Initially we used - Update <TableName> set <Column1>=0, <Column2>=0.
Later we modified the query to include a WHERE clause and did the update in batch mode such as

DECLARE @.maxCount Int
DECLARE @.iCount Int
SELECT @.MaxCount = Max(ID) FROM organizationsource
SET @.iCount = 0
WHILE (@.iCount<@.MaxCount)
BEGIN
UPDATE <tableName> set <Column1> = 0, <Column2>=0
WHERE ID between @.iCount and @.iCount+1000000
SET @.iCount = @.iCount + 1000000
END

Can you please suggest some tips to improve the update performance.
Can we do something at the SQL Server level / are there any settings at the database level for performing faster updates.

Thanks,
Loonysan

Hard to determine based on the information you've provided so far:

Is the ID field the primary index?|||

Thanks for your interest.

To Answer your Questions

1) Yes - ID field is the primary key in my table.
2) This table will not be accessed by other applications during the update process.
3) Yeah - I have the Data and Log files in different drives. (Should I keep them in different disks for better performance)
4) We are using SQL Server 2005 :)
5) The code is resides in a Stored Procedure

Thanks,
Loonysan

|||

Ok.

Are the columns you are updating indexed also?

This can slow down updates. If so, drop the index and recreate after the update has happened.

Also - make sure the following is turned off to improve performance:

auto create statistics

Bulk UPDATE on SQL Server 2000

I need to do a bulk update of 1 field in a data-table (removing
zero-padding). The update is expected to update 52.5 million records.
What techniques could I use so I can ensure
1) Consistency in the transactional log backups (every 10 mins)
2) Consistency in the full DB backup every day
3) Disk drive of Transaction logs do not get filled up completely (I suspect
even if I set rown count to 10,000 and loop through, disk-space would still
be used')
Target environment
SQL Server 2000 cluster on 2 nodes running Windows 2003 Server
(Different disk drives for data and log files)A normal set based operation will do fine. update my table set myfield =
'mynewvalue'
However, this will create significant locking so you're only going to be
this aggressive on a database that's not in use (Overnight, for most) or
write a cursor that includes some logic in it but that's going to be slow.
DatabaseAdmins.com
Databases Reliable. Available.
"Patrick" wrote:

> I need to do a bulk update of 1 field in a data-table (removing
> zero-padding). The update is expected to update 52.5 million records.
> What techniques could I use so I can ensure
> 1) Consistency in the transactional log backups (every 10 mins)
> 2) Consistency in the full DB backup every day
> 3) Disk drive of Transaction logs do not get filled up completely (I suspe
ct
> even if I set rown count to 10,000 and loop through, disk-space would stil
l
> be used')
> Target environment
> SQL Server 2000 cluster on 2 nodes running Windows 2003 Server
> (Different disk drives for data and log files)|||SQL Server takes care of consistency. To make sure you don't blow up the
transaction log, dividing the update into smaller chunks of updates (e.g.
10,000 rows at a time as you mentioned) is the right approach in general.
I'd like to add that you may have to pace your updates (e.g. sleep for some
time after each iteration) so that your transaction log backups at the
10-minute interval have a chance coming in to clear out the inactive portion
of the log for reuse. Alternative, you can backup the transaction log after
each iteration (or every so many iterations) in the loop. You need to
experiment a bit to find out the best chunk size and whether the loop withou
t
any wait time would be too tight in your particular configuration.
Also, it's certainly possible you can choose to update all the rows in a
single shot, depending on the size of your transaction log.
Linchi
"burt_king" wrote:
[vbcol=seagreen]
> A normal set based operation will do fine. update my table set myfield =
> 'mynewvalue'
> However, this will create significant locking so you're only going to be
> this aggressive on a database that's not in use (Overnight, for most) or
> write a cursor that includes some logic in it but that's going to be slow.
> --
> DatabaseAdmins.com
> Databases Reliable. Available.
>
> "Patrick" wrote:
>|||I have composed the following SQL, could you tell me what is wrong? The
Select getDate() only printed <10 dates! when I am expecting millions of
records to be updated!
DECLARE @.recCount int
SELECT @.recCount=50001
SET rowcount 50000
WHILE @.recCount>0
BEGIN
select getdate()
waitfor delay '000:00:5'
BEGIN TRAN
UPDATE
cor_transactions
SET
id_Entity = SUBSTRING(id_Entity,2,3)
WHERE
len(id_Entity)>3
and
id_Entity like '0%'
IF @.@.ERROR= 0
COMMIT TRAN
ELSE
BEGIN
ROLLBACK TRAN
print 'ERROR' + Cast(@.@.ERROR as varchar(50))
BREAK
END
SELECT @.recCount=@.@.ROWCOUNT
END
SELECT @.recCount=50001
SET rowcount 50000
WHILE @.recCount>0
BEGIN
select getdate()
waitfor delay '000:00:5'
BEGIN TRAN
UPDATE
cor_stocks
SET
id_Entity = SUBSTRING(id_Entity,2,3)
WHERE
len(id_Entity)>3
and
id_Entity like '0%'
IF @.@.ERROR= 0
COMMIT TRAN
ELSE
BEGIN
ROLLBACK TRAN
print 'ERROR' + Cast(@.@.ERROR as varchar(50))
BREAK
END
SELECT @.recCount=@.@.ROWCOUNT
END
SELECT @.recCount=50001
SET rowcount 50000
WHILE @.recCount>0
BEGIN
select getdate()
waitfor delay '000:00:5'
BEGIN TRAN
UPDATE
cor_inventory
SET
id_Entity = SUBSTRING(id_Entity,2,3)
WHERE
len(id_Entity)>3
and
id_Entity like '0%'
IF @.@.ERROR= 0
COMMIT TRAN
ELSE
BEGIN
ROLLBACK TRAN
print 'ERROR' + Cast(@.@.ERROR as varchar(50))
BREAK
END
SELECT @.recCount=@.@.ROWCOUNT
END
"Linchi Shea" wrote:
[vbcol=seagreen]
> SQL Server takes care of consistency. To make sure you don't blow up the
> transaction log, dividing the update into smaller chunks of updates (e.g.
> 10,000 rows at a time as you mentioned) is the right approach in general.
> I'd like to add that you may have to pace your updates (e.g. sleep for som
e
> time after each iteration) so that your transaction log backups at the
> 10-minute interval have a chance coming in to clear out the inactive porti
on
> of the log for reuse. Alternative, you can backup the transaction log afte
r
> each iteration (or every so many iterations) in the loop. You need to
> experiment a bit to find out the best chunk size and whether the loop with
out
> any wait time would be too tight in your particular configuration.
> Also, it's certainly possible you can choose to update all the rows in a
> single shot, depending on the size of your transaction log.
> Linchi
> "burt_king" wrote:
>

Bulk UPDATE on SQL Server 2000

I need to do a bulk update of 1 field in a data-table (removing
zero-padding). The update is expected to update 52.5 million records.
What techniques could I use so I can ensure
1) Consistency in the transactional log backups (every 10 mins)
2) Consistency in the full DB backup every day
3) Disk drive of Transaction logs do not get filled up completely (I suspect
even if I set rown count to 10,000 and loop through, disk-space would still
be used')
Target environment
SQL Server 2000 cluster on 2 nodes running Windows 2003 Server
(Different disk drives for data and log files)A normal set based operation will do fine. update my table set myfield ='mynewvalue'
However, this will create significant locking so you're only going to be
this aggressive on a database that's not in use (Overnight, for most) or
write a cursor that includes some logic in it but that's going to be slow.
--
DatabaseAdmins.com
Databases Reliable. Available.
"Patrick" wrote:
> I need to do a bulk update of 1 field in a data-table (removing
> zero-padding). The update is expected to update 52.5 million records.
> What techniques could I use so I can ensure
> 1) Consistency in the transactional log backups (every 10 mins)
> 2) Consistency in the full DB backup every day
> 3) Disk drive of Transaction logs do not get filled up completely (I suspect
> even if I set rown count to 10,000 and loop through, disk-space would still
> be used')
> Target environment
> SQL Server 2000 cluster on 2 nodes running Windows 2003 Server
> (Different disk drives for data and log files)|||SQL Server takes care of consistency. To make sure you don't blow up the
transaction log, dividing the update into smaller chunks of updates (e.g.
10,000 rows at a time as you mentioned) is the right approach in general.
I'd like to add that you may have to pace your updates (e.g. sleep for some
time after each iteration) so that your transaction log backups at the
10-minute interval have a chance coming in to clear out the inactive portion
of the log for reuse. Alternative, you can backup the transaction log after
each iteration (or every so many iterations) in the loop. You need to
experiment a bit to find out the best chunk size and whether the loop without
any wait time would be too tight in your particular configuration.
Also, it's certainly possible you can choose to update all the rows in a
single shot, depending on the size of your transaction log.
Linchi
"burt_king" wrote:
> A normal set based operation will do fine. update my table set myfield => 'mynewvalue'
> However, this will create significant locking so you're only going to be
> this aggressive on a database that's not in use (Overnight, for most) or
> write a cursor that includes some logic in it but that's going to be slow.
> --
> DatabaseAdmins.com
> Databases Reliable. Available.
>
> "Patrick" wrote:
> > I need to do a bulk update of 1 field in a data-table (removing
> > zero-padding). The update is expected to update 52.5 million records.
> >
> > What techniques could I use so I can ensure
> > 1) Consistency in the transactional log backups (every 10 mins)
> > 2) Consistency in the full DB backup every day
> > 3) Disk drive of Transaction logs do not get filled up completely (I suspect
> > even if I set rown count to 10,000 and loop through, disk-space would still
> > be used')
> >
> > Target environment
> > SQL Server 2000 cluster on 2 nodes running Windows 2003 Server
> > (Different disk drives for data and log files)|||I have composed the following SQL, could you tell me what is wrong? The
Select getDate() only printed <10 dates! when I am expecting millions of
records to be updated!
DECLARE @.recCount int
SELECT @.recCount=50001
SET rowcount 50000
WHILE @.recCount>0
BEGIN
select getdate()
waitfor delay '000:00:5'
BEGIN TRAN
UPDATE
cor_transactions
SET
id_Entity = SUBSTRING(id_Entity,2,3)
WHERE
len(id_Entity)>3
and
id_Entity like '0%'
IF @.@.ERROR= 0
COMMIT TRAN
ELSE
BEGIN
ROLLBACK TRAN
print 'ERROR' + Cast(@.@.ERROR as varchar(50))
BREAK
END
SELECT @.recCount=@.@.ROWCOUNT
END
SELECT @.recCount=50001
SET rowcount 50000
WHILE @.recCount>0
BEGIN
select getdate()
waitfor delay '000:00:5'
BEGIN TRAN
UPDATE
cor_stocks
SET
id_Entity = SUBSTRING(id_Entity,2,3)
WHERE
len(id_Entity)>3
and
id_Entity like '0%'
IF @.@.ERROR= 0
COMMIT TRAN
ELSE
BEGIN
ROLLBACK TRAN
print 'ERROR' + Cast(@.@.ERROR as varchar(50))
BREAK
END
SELECT @.recCount=@.@.ROWCOUNT
END
SELECT @.recCount=50001
SET rowcount 50000
WHILE @.recCount>0
BEGIN
select getdate()
waitfor delay '000:00:5'
BEGIN TRAN
UPDATE
cor_inventory
SET
id_Entity = SUBSTRING(id_Entity,2,3)
WHERE
len(id_Entity)>3
and
id_Entity like '0%'
IF @.@.ERROR= 0
COMMIT TRAN
ELSE
BEGIN
ROLLBACK TRAN
print 'ERROR' + Cast(@.@.ERROR as varchar(50))
BREAK
END
SELECT @.recCount=@.@.ROWCOUNT
END
"Linchi Shea" wrote:
> SQL Server takes care of consistency. To make sure you don't blow up the
> transaction log, dividing the update into smaller chunks of updates (e.g.
> 10,000 rows at a time as you mentioned) is the right approach in general.
> I'd like to add that you may have to pace your updates (e.g. sleep for some
> time after each iteration) so that your transaction log backups at the
> 10-minute interval have a chance coming in to clear out the inactive portion
> of the log for reuse. Alternative, you can backup the transaction log after
> each iteration (or every so many iterations) in the loop. You need to
> experiment a bit to find out the best chunk size and whether the loop without
> any wait time would be too tight in your particular configuration.
> Also, it's certainly possible you can choose to update all the rows in a
> single shot, depending on the size of your transaction log.
> Linchi
> "burt_king" wrote:
> > A normal set based operation will do fine. update my table set myfield => > 'mynewvalue'
> >
> > However, this will create significant locking so you're only going to be
> > this aggressive on a database that's not in use (Overnight, for most) or
> > write a cursor that includes some logic in it but that's going to be slow.
> >
> > --
> > DatabaseAdmins.com
> > Databases Reliable. Available.
> >
> >
> > "Patrick" wrote:
> >
> > > I need to do a bulk update of 1 field in a data-table (removing
> > > zero-padding). The update is expected to update 52.5 million records.
> > >
> > > What techniques could I use so I can ensure
> > > 1) Consistency in the transactional log backups (every 10 mins)
> > > 2) Consistency in the full DB backup every day
> > > 3) Disk drive of Transaction logs do not get filled up completely (I suspect
> > > even if I set rown count to 10,000 and loop through, disk-space would still
> > > be used')
> > >
> > > Target environment
> > > SQL Server 2000 cluster on 2 nodes running Windows 2003 Server
> > > (Different disk drives for data and log files)

Tuesday, March 27, 2012

Bulk Load Help - Parent Child relationship in schema

I am running a bulk load from a DTS package. I am able to insert the parent records succesfully into the article table, but I cannot get the child data to insert at all. The package returns an "executed succesfully" message, so I am having a tough time debugging. Here is my schema file, and a sample of the XML file I am trying to load. Please let me know if you spot anything in the schema I can fix (the xml file is supplied to me, and I have no control over it) All I am trying to insert in the child table (xmlTopic) is the Article_ID and the Topic_Type. Thanks in advance.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<xs:annotation>
<xs:appinfo>
<sql:relationship name="ArticleTopic"
parent="xmlARTICLE"
parent-key="ARTICLE_ID"
child="xmlTOPIC"
child-key="ARTICLE_ID" />
</xs:appinfo>
</xs:annotation>
<xs:element name="ARTICLE" sql:relation="xmlArticle" sql:key-fields="ARTICLE_ID">
<xs:complexType>
<xs:sequence>
<xs:element name="ATTRIBUTION" type="xs:string" sql:field="ATTRIBUTION"/>
<xs:element name="BLURB" type="xs:string" sql:field="BLURB"/>
<xs:element name="BODY" type="xs:string" sql:field="ARTICLE_BODY"/>
<xs:element name="BRAND" type="xs:string" sql:field="BRAND"/>
<xs:element name="BYLINE" type="xs:string" sql:field="BYLINE"/>
<xs:element name="COPYRIGHT" type="xs:string" sql:field="COPYRIGHT"/>
<xs:element name="FEATURE_BLURB" type="xs:string" sql:field="FEATURE_BLURB"/>
<xs:element name="FEATURE_IMAGE" type="xs:string" sql:field="FEATURE_IMAGE"/>
<xs:element name="HEADLINE" type="xs:string" sql:field="HEADLINE"/>
<xs:element name="NEWS_TYPE" type="xs:string" sql:field="NEWS_TYPE"/>
<xs:element name="SOURCE" type="xs:string" sql:field="SOURCE"/>
<xs:element name="TEASER" type="xs:string" sql:field="TEASER"/>
<xs:element name="URL" type="xs:string" sql:field="URL"/>
<xs:element name="TOPICS" sql:mapped="false">
<xs:complexType>
<xs:sequence>
<xs:element name="TOPIC" sql:relation="xmlTopic" sql:relationship="ArticleTopic" sql:key-fields="xmlTopicID">
<xs:complexType>
<xs:attribute name="TOPIC_TYPE" type="xs:string" sql:field="TOPIC_TYPE"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="ARTICLE_ID" type="xs:string" sql:field="ARTICLE_ID"/>
<xs:attribute name="POSTING_DATE" type="xs:string" sql:field="POSTING_DATE"/>
<xs:attribute name="ARCHIVE_DATE" type="xs:string" sql:field="ARCHIVE_DATE"/>
</xs:complexType>
</xs:element>
</xs:schema>

<?xml version="1.0"?>
<!DOCTYPE NEWSFEED SYSTEM "http://www.blah.com">
<NEWSFEED>
<ARTICLE ARTICLE_ID="531320" POSTING_DATE="08-Mar-2006" ARCHIVE_DATE="01-Mar-2007">
<NEWS_TYPE>blah</NEWS_TYPE>
<HEADLINE><![CDATA[blah]]></HEADLINE>
<BLURB><![CDATA[blah]]></BLURB>
<BYLINE><![CDATA[blah]]></BYLINE>
<BODY><![CDATA[blahblahblah]]></BODY>
<ATTRIBUTION><![CDATA[blah]]></ATTRIBUTION>
<SOURCE><![CDATA[blah]]></SOURCE>
<FEATURE_BLURB><![CDATA[blah]]></FEATURE_BLURB>
<FEATURE_IMAGE></FEATURE_IMAGE>
<TEASER><![CDATA[blah]]></TEASER>
<COPYRIGHT><![CDATA[blah]]></COPYRIGHT>
<BRAND><![CDATA[vlah]]></BRAND>
<URL><![CDATA[blah]></URL>
<TOPICS>
<TOPIC TOPIC_TYPE="BLPR"/>
<TOPIC TOPIC_TYPE="BLPR2"/>
</TOPICS>
</ARTICLE>
</NEWSFEED>

Well it turns out I answered my own question. I checked the MSDN Library(http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sqlxml3/htm/bulkload_7pv0.asp - see sql:relationship and the Key Ordering Rule), and found the following info:

"This means that in defining the <Customer> element, you must specify the CustomerID attribute in the schema before you specify <sql:relationship>. Otherwise, when an <Order> element enters into scope, XML Bulk Load generates a record for the CustOrder table; and when the XML Bulk Load reaches the </Order> end tag, it sends the record to SQL Server without the CustomerID foreign key column value."

So I put my sql:relationship at the end of the schema file, and it worked like a charm. As reference, here is my revised schema file:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:sql="urn:schemas-microsoft-com:mapping-schema">

<xsd:element name="ARTICLE" sql:relation="xmlArticle">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="ATTRIBUTION" type="xsd:string" sql:field="ATTRIBUTION"/>
<xsd:element name="BLURB" type="xsd:string" sql:field="BLURB"/>
<xsd:element name="BODY" type="xsd:string" sql:field="ARTICLE_BODY"/>
<xsd:element name="BRAND" type="xsd:string" sql:field="BRAND"/>
<xsd:element name="BYLINE" type="xsd:string" sql:field="BYLINE"/>
<xsd:element name="COPYRIGHT" type="xsd:string" sql:field="COPYRIGHT"/>
<xsd:element name="FEATURE_BLURB" type="xsd:string" sql:field="FEATURE_BLURB"/>
<xsd:element name="FEATURE_IMAGE" type="xsd:string" sql:field="FEATURE_IMAGE"/>
<xsd:element name="HEADLINE" type="xsd:string" sql:field="HEADLINE"/>
<xsd:element name="NEWS_TYPE" type="xsd:string" sql:field="NEWS_TYPE"/>
<xsd:element name="SOURCE" type="xsd:string" sql:field="SOURCE"/>
<xsd:element name="TEASER" type="xsd:string" sql:field="TEASER"/>
<xsd:element name="URL" type="xsd:string" sql:field="URL"/>
<xsd:element name="TOPIC" sql:relation="xmlTopic" sql:relationship="ArticleTopic">
<xsd:complexType>
<xsd:attribute name="TYPE2" type="xsd:string" sql:field="TopicType"/>
<xsd:attribute name="TOPIC_TYPE" type="xsd:string" sql:field="TopicID"/>
<xsd:attribute name="SIGNIFICANCE_FACTOR" type="xsd:string" sql:field="SignificanceFactor"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
<xsd:attribute name="ARTICLE_ID" type="xsd:string" sql:field="ARTICLE_ID"/>
<xsd:attribute name="POSTING_DATE" type="xsd:string" sql:field="POSTING_DATE"/>
<xsd:attribute name="ARCHIVE_DATE" type="xsd:string" sql:field="ARCHIVE_DATE"/>
</xsd:complexType>
</xsd:element>

<xsd:annotation>
<xsd:appinfo>
<sql:relationship name="ArticleTopic"
parent="xmlArticle"
parent-key="ARTICLE_ID"
child="xmlTopic"
child-key="ARTICLE_ID" />
</xsd:appinfo>
</xsd:annotation>

</xsd:schema>

sql

Sunday, March 25, 2012

Bulk Insert/Update Ideas

I need a fresh set of eyes.

On a daily basis I need to perform a bulk update. Table totals about 50,000 records with approximately 5,000 changing (deletes, edits, and new records) per day. I'd like to push just the updates somehow, but VB is too slow and I haven't found a way in to handle it in DTS. Not much experience w/ DTS.

I'm transfering between two SQL 2000 servers w/ a VB app sitting in the middle.

Any ideas?you can break the incoming file into 3 corresponding to operations (insert, update, delete) using findstr with redirection (>)

then for insert you just do a straight bulk insert, while for update and delete do a bulk insert into a staging table and then delete and update by joining it with the live table.

Bulk insert with child records

Hi,

Maybe this is a really silly problem, but I was wondering if anyone could help me find a solution.

On a daily basis I have to insert about a 1000 new (parent) records in table, with about 25000 corresponding (child) records.

The two tables a related through a parent-child relation (obviously). The primary keys in both tables are identities. The foreign key in the child table is linked to the primary key in the parent table.

I would like to use a bulk insert statement to insert the records for both tables, but the problem is that the foreign key in the child table is not automatically updated to the new value of the primary key in the parent table.
Does anyone know a work-around?? Maybe there's a better way of inserting the records?Originally posted by ChrisHens
The two tables a related through a parent-child relation (obviously). The primary keys in both tables are identities. The foreign key in the child table is linked to the primary key in the parent table.


If I understand your problem right, you want to translate an existing foreign-key-relation into a new one, based on identities?

You need to insert your parent records first, but you will have to keep your old key in your parent table. During insert of your child records, join with the parent table on your old key, and insert the newly created key as foreign key into the child table.|||Originally posted by DoktorBlue
If I understand your problem right, you want to translate an existing foreign-key-relation into a new one, based on identities?

You need to insert your parent records first, but you will have to keep your old key in your parent table. During insert of your child records, join with the parent table on your old key, and insert the newly created key as foreign key into the child table.

Yes that's exactly what I am trying to achieve. But if I am to keep my old key in the parent table, wouldn't I need an extra field? Wouldn't this also imply that after the insert of the parent and child records that I will have to somehow set the old parent key to a default value? Otherwise future joins might fail right?|||You are correct in all your points:
1) you need the old ID as an extra field, but this isn't really a problem. Often, the old ID is even functional to allow te refer to your source system.
2) if you expect to get the same parent ID in the future again, you can "flush" your old IDs after processing, or you can add some batch processing control. Options are to add a batch number (as an extra field or as unifying part of your old ID), or you can consider to make a batch control table, storing the last new ID (assuming that the identity is continue increasing) of your previous batch.

Options enough, it's depending on your situation; I'm curious what you will do.

Tuesday, March 20, 2012

Bulk Insert problem

Hello,

I am trying to insert thousands of records from a CSV file to my SQL Server database.
I am using the following to do the operation

BULK INSERT
CrimeStats.dbo.[TestDB]
FROM
'c:\Test.csv'
WITH
(
CHECK_CONSTRAINTS, FIELDTERMINATOR = ',', KEEPIDENTITY, KEEPNULLS, TABLOCK ,
ROWTERMINATOR = '\n'
)

It works fine.

My problem is I want my table in SQL server to have a Primary Key which would automatically increment. SO with every bulk insert that I would be doing every month, the Primary Key would automatically increment itself. The data in the CSV file does not have the ID field. So If I use the above script to upload the same data from the CSV file into my SQL table with the Primary Key, the BULK INSERT does not work.

It prints out the following error.

"Bulk insert data conversion error (type mismatch) for row 1, column 1 (ID)."

Is there any way that I could do what I am trying to do? The primary key is quite important in this table.

Any help on this would be much appreciated.

Thank YouSounds like you need an identity column in your table. TheBulk Insert topic in Books Online indicates that you need to specify a format file if you want SQL Server to automatically insert that identity column for you.

Terri

Monday, March 19, 2012

Bulk Insert not importing all records

Hi,
I am using the bulk insert to import over 26,000,000 records about 55 bytes
long. The insert seems to only want to import 1,780,000 records. I'm not
getting any errors and this works fine on smaller files. I have increased my
commandtimout to 260000 so I don't think that is the problem. Any help would
be appreciated.
Thanks,
EllieI don't know what your problem is, but I would be inclined to try
running multiple passes, using FIRSTROW and LASTROW to load a million
at a time. There is no guarantee that the same problem, whatever it
is, will not show up anyway though.
Roy Harvey
Beacon Falls, CT
On Tue, 2 May 2006 15:51:45 -0400, "Ellie" <nospam@.nospam.net> wrote:

>Hi,
>I am using the bulk insert to import over 26,000,000 records about 55 bytes
>long. The insert seems to only want to import 1,780,000 records. I'm not
>getting any errors and this works fine on smaller files. I have increased m
y
>commandtimout to 260000 so I don't think that is the problem. Any help woul
d
>be appreciated.
>Thanks,
>Ellie
>|||Ellie (nospam@.nospam.net) writes:
> I am using the bulk insert to import over 26,000,000 records about 55
> bytes long. The insert seems to only want to import 1,780,000 records.
> I'm not getting any errors and this works fine on smaller files. I have
> increased my commandtimout to 260000 so I don't think that is the
> problem. Any help would be appreciated.
In additions to Roy's suggestion, try the -e option. This option generates
an error file, this may reveal something.
Rather than running multiple passes with -F and -L, you can set the
batch size with -b.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Here is my bulk insert command. It works fine in query analyzer but not in
my VB6 application.
BULK INSERT dataconflict.dbo.tblTemp from 'c:\output\tt060302.txt'
WITH (BATCHSIZE=10000, FORMATFILE='c:\temp\Temp.fmt')
Where would I put the -e option?
Thank you for your help.
"Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
news:Xns97B81E3E4CCAYazorman@.127.0.0.1...
> Ellie (nospam@.nospam.net) writes:
> In additions to Roy's suggestion, try the -e option. This option generates
> an error file, this may reveal something.
> Rather than running multiple passes with -F and -L, you can set the
> batch size with -b.
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx|||Ellie (nospam@.nospam.net) writes:
> Here is my bulk insert command. It works fine in query analyzer but not in
> my VB6 application.
Hmmm. It's not that the VB6 application times out? The default timeout
from client APIs is 30 secounds.

> BULK INSERT dataconflict.dbo.tblTemp from 'c:\output\tt060302.txt'
> WITH (BATCHSIZE=10000, FORMATFILE='c:\temp\Temp.fmt')
> Where would I put the -e option?
Sorry, I did not observer that you were using BULK INSERT. My advice was
for command-line BCP.
BULK INSERT does not seem to have any option corresponding to -e. Anyway, if
it works from Query Analyzer, I don't think there are any errors in the
file.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Not sure what you mean by that. How would I change it? I made a change to
the commandtimeout to 0 so it is unlimited.
"Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
news:Xns97B8A74A8E5A5Yazorman@.127.0.0.1...
> Ellie (nospam@.nospam.net) writes:
> Hmmm. It's not that the VB6 application times out? The default timeout
> from client APIs is 30 secounds.
>
> Sorry, I did not observer that you were using BULK INSERT. My advice was
> for command-line BCP.
> BULK INSERT does not seem to have any option corresponding to -e. Anyway,
> if
> it works from Query Analyzer, I don't think there are any errors in the
> file.
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx|||Ellie (nospam@.nospam.net) writes:
> Not sure what you mean by that. How would I change it? I made a change to
> the commandtimeout to 0 so it is unlimited.
If you already have set the commandtimeout to 0, I'm afraid that I have
no idea what is going on.
If you have the proper access on the server, you could set up a Profiler
trace, and include the events in the Errors and Exception group, to
see if this brings up something.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Hi Erland,
Thanks for your help. I have managed to get all of the records imported by
changing the batchsize from 10000 to 100000. I don't know why that would
make a difference though.
"Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
news:Xns97B917BE14B6Yazorman@.127.0.0.1...
> Ellie (nospam@.nospam.net) writes:
> If you already have set the commandtimeout to 0, I'm afraid that I have
> no idea what is going on.
> If you have the proper access on the server, you could set up a Profiler
> trace, and include the events in the Errors and Exception group, to
> see if this brings up something.
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx|||Ellie (nospam@.nospam.net) writes:
> Thanks for your help. I have managed to get all of the records imported by
> changing the batchsize from 10000 to 100000. I don't know why that would
> make a difference though.
Neither have I!
I'm glad to hear that you got it working.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

Bulk insert is all or nothing?

Hi, I ran query 'Bulk insert mytable from myFile with (FIRE_TRIGGERS)'.

The problems are,
1.It does nothing if exist duplication key records. There is no option to skip the duplications. What else is possible to skip duplicated insertion and go next record when bulk insert?

2. The triggers are not fired even if bulk insert success.

My goal is that very large data should be loaded at once and use trigger.

The trigger is fired after bulk insert executed.
But, still remained some problems.
The result of executing trigger is affected only the last record of source data file. It seems that the trigger definition has logical or symantical problems. Any one help is very appreciated.

Here is my definition of trigger.
Can I control all of the inserted recorcd in trigger definition?

create table myTable
(
id int,
value1 int,
value2 int,
primary key(id)
);

create table myTempTable
(
id int,
value1 int,
value2 int
);

CREATE TRIGGER mytrigger ON myTempTable
INSTEAD OF INSERT
AS
BEGIN
PRINT 'trigger mytrigger'
DECLARE @.id AS int, @.value1 AS int, @.value2 AS int
SELECT @.id = INSERTED.id,
@.value1 = INSERTED.value1,
@.value2 = INSERTED.value2
FROM INSERTED

PRINT @.id
PRINT @.value1
PRINT @.value2

IF EXISTS(SELECT * FROM myTable WHERE id = @.id)
BEGIN
PRINT 'trigger EXISTS'
PRINT 'UPDATE'
UPDATE myTable SET value = value + @.value,outbKbps =outbKbps + @.outbKbps WHERE id=@.id
END
ELSE
BEGIN
PRINT 'trigger NOT EXISTS'
PRINT 'trigger INSERT'
INSERT INTO myTableVALUES(@.id,@.value1,@.value2)
END
END
GO

bulk insert myTempTable from 'c:\bulk_myTable.dat' with (FIRE_TRIGGERS);

-- bulk_myTable.dat file's contents --
1 100 200
1 100 200
1 100 200
1 100 200
1 100 200

From Books Online, topic: "Using bcp and BULK INSERT"

Triggers are fired once for each batch in the bulk copy operation. The inserted table passed to the trigger contains all of the rows inserted by the batch. Specify FIRE_TRIGGERS only when bulk copying into a table with INSERT and INSTEAD OF triggers that support multiple row inserts.

Your trigger fires only one time for the entire batch -not for each row in the batch.

Your trigger 'assumes' there is, and is designed to handle, only one row in the inserted table, and therefore will NOT do as you desire. It couldn't possibly work for a bulk insert of more than one row.

You should 're-design' the trigger to handle multiple rows at a time. If you provide, in a new posting, the table DDL, some sample data in the form of insert statements, and a statement of what you are attempting to accomplish, perhaps some here can help you create a trigger that will work for you.

Hopefully, this answered your question.

|||

I solved the number of 2 from my question in this thread.

I use the 'AFTER' instead of 'INSTEAD OF' trigger for getting the bulk insert result record.
And, in trigger definition, using the cursor, get the recordset that I want to get.
In the end, insert or update to the target table record by record.
I got this as hint from your commant. Thank you very much.

Here is the sample.

CREATE TRIGGER TRG_MY_TABLE ON MyTempTable
AFTER INSERT
AS
BEGIN

DECLARE @.id AS INT,
@.value1 AS INT,
@.value2 AS INT


DECLARE CursorMyTable CURSOR FOR
SELECT id AS cur_id, value1 AS cur_value1, value2 AS cur_value2
FROM MyTempTable

OPEN CursorMyTable

FETCH NEXT FROM CursorMyTable
INTO @.id,@.value1,@.value2

-
IF EXISTS(SELECT * FROM MyTable WHERE id=@.id)
BEGIN
UPDATE MyTable
SET value1= value1+ @.value1,
value2= value2+ @.value2
WHERE id=@.id

END
ELSE
BEGIN
INSERT INTO MyTable VALUES(@.id,@.value1,@.value2)
END
-


WHILE @.@.FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM CursorMyTable
INTO @.id,@.value1,@.value2

IF EXISTS(SELECT * FROM MyTable WHERE id=@.id)
BEGIN
UPDATE MyTable
SET value1= value1+ @.value1,
value2= value2+ @.value2
WHERE id=@.id

END
ELSE
BEGIN
INSERT INTO MyTable VALUES(@.id,@.value1,@.value2)
END
-

END

CLOSE CursorMyTable

DEALLOCATE CursorMyTable
END

|||

I would highly recommend NOT using a CURSOR in a TRIGGER.

It would be far better to load the data into a 'Staging' table, and then process the data as needed. Stepping through a CURSOR in the context of a TRIGGER (meaning during a TRANSACTION) will hold a lot of locks and resources -most likely, unnecessarily.

Just not a good idea.

|||Thank you, but could you more explain about the 'Staging' table?|||

A 'Staging' table most likely would have the same columns as the final production table -but datatypes may be different. Data is loaded into the Staging table, and then cleansed, conformed, and moved to the production table.

This is a very common ETL operation.

Thursday, March 8, 2012

Bulk Insert fails

I am using SQL Server 2005 Management Studio Express.I am trying to insert records in bulk into "students" table.

Students:
uniqueid varchar(9) (primary Key)
lname varchar(35)
fname varchar(35)

My problem is when one record from the bulk record already exists in Students table all the bulk insert fails. I dont want that. I want rest of the records to be inserted smoothly with no error.

How can I do it....Is there any disadvantage if i do this?

You could bulk insert into a staging table and then do the logic to insert only non-duplicated keys. I rarely (if ever) insert directly into a "master table". Once data is in the staging table you can do a simple insert.

Insert into Students
Select uniqueid, lname, fname, ....
from staging_Students
where uniqueid not in (select uniqueid from Students)

Drop the staging table after you are done, or leave it there to determine why you are getting duplicated keys from the insert file...

|||

I am using staging table and inserting using not in condition...but i am trying to see if there is a way around...the reason is bc i think the performance of query will come down if i do again select....will the performance go down?students table will have 60000 records...

|||

You could also use Openrowset with the BULK option (see books online for details). You would have to define a format file to use for the BULK option.

Insert into Students
Select uniqueid, lname, fname, ....
From Openrowset(BULK bulk parameters) as A
Where uniqueid not in (select uniqueid from Students)

|||

Yes, the performance depends on the number of rows in the main table and the inserted rwos. But another option is to remove the primary key on the uniqueid column and create an unique index with the ignore_dup_key option ON. This will result in the duplicate rows from being ignored during BULK INSERT. This will eliminate the additional join using staging table approach. In any case, you should use the staging table if you have more complex data cleaning tasks to perform.

So do the following:

1. Drop primary key on uniqueid column

2. Add unique index like:

create unique index ix_uq_uniqueid on Students(uniqueid) with ignore_dup_key = on

3. Now, bulk insert as before and the duplicate rows will be ignored automatically.

|||

umachandar...students table can have 60000 records. At a time I can insert 300 records into that. This is my scenario...can you tell which approach is better to follow( using ignore_dup_key or use not in condition to check duplicates). Do I need staging table if i user ignore_dup_key option.? I am having clustered index on uniqueid column in students table rite now.

Scenario:

60 users will be using my application. each user can upload a .csv file with 300 records at maximum.

This is what i am doing rite now....when the user uploads a .csv file from front end the .net application will invoke sqlbulkcopy class built into .net 2.0 and does a bulk insert ot 300 records into staging table. After that i invoke a stored procedure which puts the data into 3 different tables. so my procedure will have 3 insert statements(with not in conditions). After successful insertion i delete the data from the staging table for that user. the number of users and records in students table can grow up further in furture...

or should I user the ignore_dup_key option and avoid the staging table?

Thanks...

Saturday, February 25, 2012

BULK INSERT & DIRTY BUFFERS

Hi all

Using SQL 2000 MSDE

I'm bulk inserting about 3.200.000 records into a table

unfortunately all memory dissapears and never returns the dirty buffers count goes up to 48000 approx.

any ideas on how to rectify this ..... ?sqlserver is designed to take up as much as memory and only releases it back if the system needs it. If you must, restarting sqlserver will force the release.
Normally, I wouldn't want to pump that much data into the db in one shot. Rather, I would do it in batches. Please take a look at -b option of bcp or ROWS_PER_BATCH of bulk insert.|||Thanks for that
I have already figured out that restarting the service will do the trick .....
but it is a live database with many users .... (they will not thank me for doing such things)
thanks anyway ... i'll keep searching

BULK INSERT - Urgent

I have a tab delimeted file which i BCP into a temp table using BULK INSERT
When i use DTS Transform data task i get all 7000 records in the table
In DTS data transform i choose Column Delimeter is a tab ann row delimeter
is {CR}{LF}
When i do Bulk insert in using command below a lot of these records are
combined with previous records dud to improper row terminators on some records
How do i make this work in BULK INSERT same way as it works in DTS
BULK INSERT #stage_obligor_exposure
FROM "k:\sqldb2\ermg\data\apr2005\exposures\test1.txt"
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = "\t",
ROWTERMINATOR = "\n"
)
Pls help..........This is a multi-part message in MIME format.
--020900050805040007080207
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
One thing I noticed is that you use "\r\n" as your row terminator in
your DTS package but only "\n" in your BULK INSERT statement. Perhaps
every row in your input file doesn't have a "\n" to terminate but only a
"\r" (from memory, although it's been a while so I could be wrong,
typically text files generated with Unix/Linux tools only use a "\r"
(ASCII 13) to terminate a line). I don't know why \r\n would work in
the DTS package if a line only has a \r but maybe you could try
different combinations of row terminators for your BULK INSERT statement
(like "\n", "\r\n", "\r").
--
*mike hodgson* |/ database administrator/ | mallesons stephen jaques
*T* +61 (2) 9296 3668 |* F* +61 (2) 9296 3885 |* M* +61 (408) 675 907
*E* mailto:mike.hodgson@.mallesons.nospam.com |* W* http://www.mallesons.com
Sanjay wrote:
>I have a tab delimeted file which i BCP into a temp table using BULK INSERT
>When i use DTS Transform data task i get all 7000 records in the table
>In DTS data transform i choose Column Delimeter is a tab ann row delimeter
>is {CR}{LF}
>When i do Bulk insert in using command below a lot of these records are
>combined with previous records dud to improper row terminators on some records
>How do i make this work in BULK INSERT same way as it works in DTS
>BULK INSERT #stage_obligor_exposure
> FROM "k:\sqldb2\ermg\data\apr2005\exposures\test1.txt"
> WITH
> (
> FIRSTROW = 2,
> FIELDTERMINATOR = "\t",
> ROWTERMINATOR = "\n"
> )
>Pls help..........
>
>
--020900050805040007080207
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 8bit
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=UTF-8" http-equiv="Content-Type">
</head>
<body bgcolor="#ffffff" text="#000000">
<tt>One thing I noticed is that you use "\r\n" as your row terminator
in your DTS package but only "\n" in your BULK INSERT statement.Â
Perhaps every row in your input file doesn't have a "\n" to terminate
but only a "\r" (from memory, although it's been a while so I could be
wrong, typically text files generated with Unix/Linux tools only use a
"\r" (ASCII 13) to terminate a line). I don't know why \r\n would work
in the DTS package if a line only has a \r but maybe you could try
different combinations of row terminators for your BULK INSERT
statement (like "\n", "\r\n", "\r").</tt><br>
<div class="moz-signature">
<title></title>
<meta http-equiv="Content-Type" content="text/html; ">
<p><span lang="en-au"><font face="Tahoma" size="2">--<br>
</font> </span><b><span lang="en-au"><font face="Tahoma" size="2">mike
hodgson</font></span></b><span lang="en-au"> <font face="Tahoma"
size="2">|</font><i><font face="Tahoma"> </font><font face="Tahoma"
size="2"> database administrator</font></i><font face="Tahoma" size="2">
| mallesons</font><font face="Tahoma"> </font><font face="Tahoma"
size="2">stephen</font><font face="Tahoma"> </font><font face="Tahoma"
size="2"> jaques</font><font face="Tahoma"><br>
</font><b><font face="Tahoma" size="2">T</font></b><font face="Tahoma"
size="2"> +61 (2) 9296 3668 |</font><b><font face="Tahoma"> </font><font
face="Tahoma" size="2"> F</font></b><font face="Tahoma" size="2"> +61
(2) 9296 3885 |</font><b><font face="Tahoma"> </font><font
face="Tahoma" size="2">M</font></b><font face="Tahoma" size="2"> +61
(408) 675 907</font><br>
<b><font face="Tahoma" size="2">E</font></b><font face="Tahoma" size="2">
<a href="http://links.10026.com/?link=mailto:mike.hodgson@.mallesons.nospam.com">
mailto:mike.hodgson@.mallesons.nospam.com</a> |</font><b><font
face="Tahoma"> </font><font face="Tahoma" size="2">W</font></b><font
face="Tahoma" size="2"> <a href="http://links.10026.com/?link=/">http://www.mallesons.com">
http://www.mallesons.com</a></font></span> </p>
</div>
<br>
<br>
Sanjay wrote:
<blockquote cite="midBC983130-5E18-4E77-92BB-0FFC20421FAA@.microsoft.com"
type="cite">
<pre wrap="">I have a tab delimeted file which i BCP into a temp table using BULK INSERT
When i use DTS Transform data task i get all 7000 records in the table
In DTS data transform i choose Column Delimeter is a tab ann row delimeter
is {CR}{LF}
When i do Bulk insert in using command below a lot of these records are
combined with previous records dud to improper row terminators on some records
How do i make this work in BULK INSERT same way as it works in DTS
BULK INSERT #stage_obligor_exposure
FROM "k:\sqldb2\ermg\data\apr2005\exposures\test1.txt"
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = "\t",
ROWTERMINATOR = "\n"
)
Pls help..........
</pre>
</blockquote>
</body>
</html>
--020900050805040007080207--|||I have gotten this bulk insert statement to work and all you would have to do
is change the fieldterminator to '\t'. Notice the file I was working with
was CSV and it had "," for field termination. You can try using a FORMAT
file parameter but so far I have been unsuccessful in getting that to work.
You can make a format file from the table using the following code:
EXEC master.dbo.xp_cmdshell 'BCP sqlsrv.dbo.SystemTemp FORMAT -Usa
-Ppassword -N -fc:\TBL_Format.fmt'
Which will make you a format file of the table you are trying to bulk import
into.
---
BULK INSERT [dbo].[SystemTemp]
FROM 'c:\SystemTempIn.csv'
WITH
(
DATAFILETYPE = 'char',
FIELDTERMINATOR = '","',
FIRSTROW = 2,
ROWTERMINATOR = '"\n'
)
"Sanjay" wrote:
> I have a tab delimeted file which i BCP into a temp table using BULK INSERT
> When i use DTS Transform data task i get all 7000 records in the table
> In DTS data transform i choose Column Delimeter is a tab ann row delimeter
> is {CR}{LF}
> When i do Bulk insert in using command below a lot of these records are
> combined with previous records dud to improper row terminators on some records
> How do i make this work in BULK INSERT same way as it works in DTS
> BULK INSERT #stage_obligor_exposure
> FROM "k:\sqldb2\ermg\data\apr2005\exposures\test1.txt"
> WITH
> (
> FIRSTROW = 2,
> FIELDTERMINATOR = "\t",
> ROWTERMINATOR = "\n"
> )
> Pls help..........
>

Friday, February 24, 2012

Bulk insert

hi all,
I am using bulk insert to insert records from a text file to a table.
The text file contains # or comma as fieldterminator. how to handle
both the field terminators in a stored procedure.
thanks to all,
kc.Do you mean that some columns are seperated by # and some columns are
seperated by commas? Or that there's no pattern at all to the separators?
-Paul
<kc4u7@.yahoo.com> wrote in message
news:1141886075.704092.89530@.i39g2000cwa.googlegroups.com...
> hi all,
> I am using bulk insert to insert records from a text file to a table.
> The text file contains # or comma as fieldterminator. how to handle
> both the field terminators in a stored procedure.
> thanks to all,
> kc.
>|||Hi Paul,
I am using bulk insert to transfer hugh data from a .dbf file to my sql
server table. Can you guide me in this case what shoud I specify as
fieldterminator and rowterminator?
Thanks in advance.
Regards,
Shailesh
"Paul Nielsen (MVP)" wrote:

> Do you mean that some columns are seperated by # and some columns are
> seperated by commas? Or that there's no pattern at all to the separators?
> -Paul
>
> <kc4u7@.yahoo.com> wrote in message
> news:1141886075.704092.89530@.i39g2000cwa.googlegroups.com...
>
>|||Shailesh wrote:
> Hi Paul,
> I am using bulk insert to transfer hugh data from a .dbf file to my sql
> server table. Can you guide me in this case what shoud I specify as
> fieldterminator and rowterminator?
> Thanks in advance.
> Regards,
> Shailesh
>
Shailesh,
Please don't post the same question multiple times. I answered in one
of the several other threads you posted to. I'll leave you to work out
which it was! :-(
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--

Sunday, February 19, 2012

Bulk Deletes and Bulk Copy

We are currently facing some issues with bulk deletes of records during
Archiving.
Our application logs all the requests and responses in the log tables. After
10 days these requests are supposed to be archived (to a different database
‘Archiving Database’ on the same server) and deleted from the OSS database.
‘Archiving’ process is taken care by a stored procedure. Also, please note
that there are certain restrictions (like request must have been
successfully) on a request before it can be archived and deleted.
What is the problem?
We are facing issues both while copying the data to archiving database and
deleting the data from Main database.
1. When records are to be copied from Main to Archiving database, locks are
acquired on the log tables in Main database and the log tables are blocked
there by hindering any further activity.
2. The same problem occurs while deleting the records from log tables.
What are we looking for?
Would be great to have some best practices around archiving and bulk deletes
in SQL server.
"Sachin Surana" schrieb:

> We are currently facing some issues with bulk deletes of records during
> Archiving.
> Our application logs all the requests and responses in the log tables. After
> 10 days these requests are supposed to be archived (to a different database
> ‘Archiving Database’ on the same server) and deleted from the OSS database.
> ‘Archiving’ process is taken care by a stored procedure. Also, please note
> that there are certain restrictions (like request must have been
> successfully) on a request before it can be archived and deleted.
> What is the problem?
> We are facing issues both while copying the data to archiving database and
> deleting the data from Main database.
> 1. When records are to be copied from Main to Archiving database, locks are
> acquired on the log tables in Main database and the log tables are blocked
> there by hindering any further activity.
> 2. The same problem occurs while deleting the records from log tables.
> What are we looking for?
> Would be great to have some best practices around archiving and bulk deletes
> in SQL server.
Excerpt from the books online (page 'Lock Compatibility'):
The bulk update (BU) lock is compatible only with schema stability (Sch-S)
and other bulk update (BU) locks.
|||Hmm.. i understand, but that is the problem. Do you mean we should use bulk
update lock?
Is there faster way for bulk delete, bulk update?
Regards,
Sachin
"Christian Donner" wrote:

> "Sachin Surana" schrieb:
>
> Excerpt from the books online (page 'Lock Compatibility'):
> The bulk update (BU) lock is compatible only with schema stability (Sch-S)
> and other bulk update (BU) locks.

Bulk Deletes and Bulk Copy

We are currently facing some issues with bulk deletes of records during
Archiving.
Our application logs all the requests and responses in the log tables. After
10 days these requests are supposed to be archived (to a different database
‘Archiving Database’ on the same server) and deleted from the OSS databa
se.
‘Archiving’ process is taken care by a stored procedure. Also, please no
te
that there are certain restrictions (like request must have been
successfully) on a request before it can be archived and deleted.
What is the problem?
We are facing issues both while copying the data to archiving database and
deleting the data from Main database.
1. When records are to be copied from Main to Archiving database, locks are
acquired on the log tables in Main database and the log tables are blocked
there by hindering any further activity.
2. The same problem occurs while deleting the records from log tables.
What are we looking for?
Would be great to have some best practices around archiving and bulk deletes
in SQL server."Sachin Surana" schrieb:

> We are currently facing some issues with bulk deletes of records during
> Archiving.
> Our application logs all the requests and responses in the log tables. Aft
er
> 10 days these requests are supposed to be archived (to a different databas
e
> ‘Archiving Database’ on the same server) and deleted from the OSS data
base.
> ‘Archiving’ process is taken care by a stored procedure. Also, please
note
> that there are certain restrictions (like request must have been
> successfully) on a request before it can be archived and deleted.
> What is the problem?
> We are facing issues both while copying the data to archiving database and
> deleting the data from Main database.
> 1. When records are to be copied from Main to Archiving database, locks ar
e
> acquired on the log tables in Main database and the log tables are blocked
> there by hindering any further activity.
> 2. The same problem occurs while deleting the records from log tables.
> What are we looking for?
> Would be great to have some best practices around archiving and bulk delet
es
> in SQL server.
Excerpt from the books online (page 'Lock Compatibility'):
The bulk update (BU) lock is compatible only with schema stability (Sch-S)
and other bulk update (BU) locks.|||Hmm.. i understand, but that is the problem. Do you mean we should use bulk
update lock?
Is there faster way for bulk delete, bulk update?
Regards,
Sachin
"Christian Donner" wrote:

> "Sachin Surana" schrieb:
>
> Excerpt from the books online (page 'Lock Compatibility'):
> The bulk update (BU) lock is compatible only with schema stability (Sch-S)
> and other bulk update (BU) locks.

Bulk Deletes and Bulk Copy

We are currently facing some issues with bulk deletes of records during
Archiving.
Our application logs all the requests and responses in the log tables. After
10 days these requests are supposed to be archived (to a different database
â'Archiving Databaseâ' on the same server) and deleted from the OSS database.
â'Archivingâ' process is taken care by a stored procedure. Also, please note
that there are certain restrictions (like request must have been
successfully) on a request before it can be archived and deleted.
What is the problem?
We are facing issues both while copying the data to archiving database and
deleting the data from Main database.
1. When records are to be copied from Main to Archiving database, locks are
acquired on the log tables in Main database and the log tables are blocked
there by hindering any further activity.
2. The same problem occurs while deleting the records from log tables.
What are we looking for?
Would be great to have some best practices around archiving and bulk deletes
in SQL server."Sachin Surana" schrieb:
> We are currently facing some issues with bulk deletes of records during
> Archiving.
> Our application logs all the requests and responses in the log tables. After
> 10 days these requests are supposed to be archived (to a different database
> â'Archiving Databaseâ' on the same server) and deleted from the OSS database.
> â'Archivingâ' process is taken care by a stored procedure. Also, please note
> that there are certain restrictions (like request must have been
> successfully) on a request before it can be archived and deleted.
> What is the problem?
> We are facing issues both while copying the data to archiving database and
> deleting the data from Main database.
> 1. When records are to be copied from Main to Archiving database, locks are
> acquired on the log tables in Main database and the log tables are blocked
> there by hindering any further activity.
> 2. The same problem occurs while deleting the records from log tables.
> What are we looking for?
> Would be great to have some best practices around archiving and bulk deletes
> in SQL server.
Excerpt from the books online (page 'Lock Compatibility'):
The bulk update (BU) lock is compatible only with schema stability (Sch-S)
and other bulk update (BU) locks.|||Hmm.. i understand, but that is the problem. Do you mean we should use bulk
update lock?
Is there faster way for bulk delete, bulk update?
Regards,
Sachin
"Christian Donner" wrote:
> "Sachin Surana" schrieb:
> > We are currently facing some issues with bulk deletes of records during
> > Archiving.
> >
> > Our application logs all the requests and responses in the log tables. After
> > 10 days these requests are supposed to be archived (to a different database
> > â'Archiving Databaseâ' on the same server) and deleted from the OSS database.
> > â'Archivingâ' process is taken care by a stored procedure. Also, please note
> > that there are certain restrictions (like request must have been
> > successfully) on a request before it can be archived and deleted.
> >
> > What is the problem?
> >
> > We are facing issues both while copying the data to archiving database and
> > deleting the data from Main database.
> >
> > 1. When records are to be copied from Main to Archiving database, locks are
> > acquired on the log tables in Main database and the log tables are blocked
> > there by hindering any further activity.
> >
> > 2. The same problem occurs while deleting the records from log tables.
> >
> > What are we looking for?
> >
> > Would be great to have some best practices around archiving and bulk deletes
> > in SQL server.
> Excerpt from the books online (page 'Lock Compatibility'):
> The bulk update (BU) lock is compatible only with schema stability (Sch-S)
> and other bulk update (BU) locks.

Bulk Delete

we are trying to delete data from a huge 75 million records table
it takes 4hr to prune data

delete from Company where recordid in (select top 10000 recordid from
recordid_Fed3 where flag = 0)

we have a loop that prunes 10000 records at a time in a while loop
let me know if there is a better way to acheive thisIf you just want to delete *every* row in the table you can use
TRUNCATE TABLE :

<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_ta-tz_2hk5.asp
If you want to selectively delete rows, that won't work, though. If
you want to delete most of the rows (but not all of them) you could
insert the ones you want to keep into some other (temporary) table,
truncate the main table, then insert the rows back.|||kumar (svengala@.gmail.com) writes:
> we are trying to delete data from a huge 75 million records table
> it takes 4hr to prune data
> delete from Company where recordid in (select top 10000 recordid from
> recordid_Fed3 where flag = 0)
> we have a loop that prunes 10000 records at a time in a while loop
> let me know if there is a better way to acheive this

Rather than using SELECT TOP, try use a condition that matches the clustered
index and slice that up in intervals. Assume that the clustered index is
on recordid, and that this is an integer you would do:

SELECT @.recordid = MIN(recordid) FROM Company (WHERE flag = 0),
@.increment = 100000
WHILE EXISTS (SELECT * FROM Company WHERE recordid = @.recordid)
BEGIN
DELETE Company
WHERE recordid BETWEEN @.recordid AND @.recordid + @.increment - 1
AND flag = 0
SELECT @.recordid = @.recordid + @.increment
END

In this way you are only scanning the table once for rows to delete.

If you anticipate that you will delete more rows than you will retain,
you could create a new table, and insert the rows to keep. In this case
you need to make sure that you also bring with you constraints, indexes,
and triggers, and you will have to move referencing foreign keys. The
insert can be further speedied up by using SELECT INTO, but SELECT INTO
may not give you a faithful copy of the table.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

Bulk Copy Program

Hi
I have a flat file that contains records many records. The first field
states the following for each record:
'I' = insert
'U' = update
'D' = delete
Is it possible for the BCP to achieve this objective? I know there be some
coding involved. I also noticed that there's an ODBC API that I can use in
..NET.
I'm not to sure but can BCP delete or update records?
Thanks in advance
Ross
Hi,
BCP can just copy the data into a file and then using a BCP IN loading back
to a table. Using this you cant dor a delete or update.
Thanks
Hari
MCDBA
"Ross Pellegrino" wrote:

> Hi
> I have a flat file that contains records many records. The first field
> states the following for each record:
> 'I' = insert
> 'U' = update
> 'D' = delete
> Is it possible for the BCP to achieve this objective? I know there be some
> coding involved. I also noticed that there's an ODBC API that I can use in
> ..NET.
> I'm not to sure but can BCP delete or update records?
> Thanks in advance
> Ross
>
>
|||Thanks for the info.
Ross
"Hari Prasad" <HariPrasad@.discussions.microsoft.com> wrote in message
news:4352FAE8-F9EE-4C92-8E89-E372F442538B@.microsoft.com...
> Hi,
> BCP can just copy the data into a file and then using a BCP IN loading
back[vbcol=seagreen]
> to a table. Using this you cant dor a delete or update.
> Thanks
> Hari
> MCDBA
>
> "Ross Pellegrino" wrote:
some[vbcol=seagreen]
in[vbcol=seagreen]

Thursday, February 16, 2012

BULK COPY - in memory data

Hi,

I have a set of records in application memory seperated by a record terminator '\n'. I can write the memory stream to a local disk file and call bcp api functions to load the file in to SQL server. But how do I transfer the in memory data directly to the SQL server, without writing to a data file, using ODBC. I am not using any .Net Framework classes in my code. The SQL server and application server(generating the data records) are on two different physical servers connected through network. I am trying to figureout the fastest and efficient way to load the data to SQL server from a remote application server. Thanks for your help.

Srini

Hi Srini,

You need to use the In-Memory BCP APIs for this purpose. You can look up the MSDN documentation for bcp_bind function which also has a small sample code about how to do it. Here is a link:

http://msdn2.microsoft.com/ru-ru/library/ms131401.aspx

Thanks

Waseem

Buld Data load import

HI

I have a table XYZ that needs to contain a million records as operational data.

XYZ has a column named SLOT_VALUE which has values 1,2,3....100,000

What is the easiset way to bulk load this information in the shortest possible time...

Insert scripts/ Batch program like if..while loop takes heck lot of time....

Hello,

If you mean that you just want to populate that table with incrementing values from 1 to 1MIL, then the easiest would be to execute something like

select top 1000000 identity(int,1,1) as Num
into TempNumTable
from syscolumns c1
cross join syscolumns c2
cross join syscolumns c3
cross join syscolumns c4
... etc

You can't just directly insert into your already created table as the identity() function need a select into clause. You can just insert from the newly created table into your XYZ operational table.

If this is not what you mean, and you have a flat file that you want to bulk load into the table, have a look at the BULK INSERT command (use TABLOCK and consider dropping any existing indexes on the table prior to the load).

Cheers,

Rob


|||

Guess the easiest is to have t-sql script using a while loop...I thought of bcp but then I need to create a file...that would be redundant...

Anyhow thnx for the post.

|||

No worries. Just remember that performing this operation within a while loop will entail 1 million individual inserts! The set based solution described above would be much faster and much more efficient. If this is a once-off operation, then it's probably not an issue.

Cheers,
Rob