Showing posts with label updated. Show all posts
Showing posts with label updated. Show all posts

Wednesday, March 28, 2012

Optimizing a large

Hi
I'm running a script that updates the same column on every row in a huge table. The table is being updated with data from another table in another database, but they are in the same SQL instance
The log and data files for the database being read from are on an internal drive (D:\). The log and datafiles for the database being updated are on an external SAN (X:\
Would any of the following speed the process up significantly
1)Remove the indexes from the table being updated
2)Set the recovery model to 'simple' on the database being updated
3)Put the log and data files on the database being updated on different physical disks (not necessary i believe if I perform number 2)
thanks
KevinKevin,
1. If the column that you are updating has an index on it you might
consider dropping it until after the update.
2. This won't affect in any way the number of items logged or the amount of
data logged during an Update. If you do the update in one transaction it
won't matter either way.
3. It's always best to place the Log and Data files on separate drive
arrays. It makes no difference where the log for the one being read from
are since the log is not used for reads.
I would recommend you attempt the Updates in smaller batches. This will
keep the log in check and usually results in a faster overall operation.
You can usually achieve this with a loop of some sort.
--
Andrew J. Kelly
SQL Server MVP
"Kevin" <anonymous@.discussions.microsoft.com> wrote in message
news:715A5D36-5F4F-43D5-8B5B-854B711F3A9A@.microsoft.com...
> Hi,
> I'm running a script that updates the same column on every row in a huge
table. The table is being updated with data from another table in another
database, but they are in the same SQL instance.
> The log and data files for the database being read from are on an internal
drive (D:\). The log and datafiles for the database being updated are on an
external SAN (X:\)
> Would any of the following speed the process up significantly?
> 1)Remove the indexes from the table being updated?
> 2)Set the recovery model to 'simple' on the database being updated?
> 3)Put the log and data files on the database being updated on different
physical disks (not necessary i believe if I perform number 2).
> thanks,
> Kevin|||Thanks for your response
Does the frequency of log checkpoints significantly slow down a long running update statement? Should I create a large transaction log that will not need to dynamically grow and set the recovery interval to a high value so that the frequency of checkpoints is reduced
thanks
Kevin|||Kevin,
First off you should always have the log file larger than it needs to be for
any given operation. Anytime it has to grow it will impact performance to
some degree. As for check points that depends. Checkpoints certainly can
add overhead to the system, especially disk IO and CPU. Whether they have a
large negative effect on your situation is hard to say from here. If you
make a large recovery interval it will most definitely adversely affect the
other users when it does happen as there will be a lot more to do at one
time. The key in your situation is to do the updates in smaller batches.
Andrew J. Kelly
SQL Server MVP
"Kevin" <anonymous@.discussions.microsoft.com> wrote in message
news:4A65CF81-2DD6-4F53-AA7A-E7B00FF50CE2@.microsoft.com...
> Thanks for your response.
> Does the frequency of log checkpoints significantly slow down a long
running update statement? Should I create a large transaction log that will
not need to dynamically grow and set the recovery interval to a high value
so that the frequency of checkpoints is reduced?
> thanks,
> Kevin

Optimizing a large

Hi,
I'm running a script that updates the same column on every row in a huge tab
le. The table is being updated with data from another table in another datab
ase, but they are in the same SQL instance.
The log and data files for the database being read from are on an internal d
rive (D:\). The log and datafiles for the database being updated are on an e
xternal SAN (X:\)
Would any of the following speed the process up significantly?
1)Remove the indexes from the table being updated?
2)Set the recovery model to 'simple' on the database being updated?
3)Put the log and data files on the database being updated on different phys
ical disks (not necessary i believe if I perform number 2).
thanks,
KevinKevin,
1. If the column that you are updating has an index on it you might
consider dropping it until after the update.
2. This won't affect in any way the number of items logged or the amount of
data logged during an Update. If you do the update in one transaction it
won't matter either way.
3. It's always best to place the Log and Data files on separate drive
arrays. It makes no difference where the log for the one being read from
are since the log is not used for reads.
I would recommend you attempt the Updates in smaller batches. This will
keep the log in check and usually results in a faster overall operation.
You can usually achieve this with a loop of some sort.
Andrew J. Kelly
SQL Server MVP
"Kevin" <anonymous@.discussions.microsoft.com> wrote in message
news:715A5D36-5F4F-43D5-8B5B-854B711F3A9A@.microsoft.com...
quote:

> Hi,
> I'm running a script that updates the same column on every row in a huge

table. The table is being updated with data from another table in another
database, but they are in the same SQL instance.
quote:

> The log and data files for the database being read from are on an internal

drive (D:\). The log and datafiles for the database being updated are on an
external SAN (X:\)
quote:

> Would any of the following speed the process up significantly?
> 1)Remove the indexes from the table being updated?
> 2)Set the recovery model to 'simple' on the database being updated?
> 3)Put the log and data files on the database being updated on different

physical disks (not necessary i believe if I perform number 2).
quote:

> thanks,
> Kevin
|||Thanks for your response.
Does the frequency of log checkpoints significantly slow down a long running
update statement? Should I create a large transaction log that will not nee
d to dynamically grow and set the recovery interval to a high value so that
the frequency of checkpoint
s is reduced?
thanks,
Kevin|||Kevin,
First off you should always have the log file larger than it needs to be for
any given operation. Anytime it has to grow it will impact performance to
some degree. As for check points that depends. Checkpoints certainly can
add overhead to the system, especially disk IO and CPU. Whether they have a
large negative effect on your situation is hard to say from here. If you
make a large recovery interval it will most definitely adversely affect the
other users when it does happen as there will be a lot more to do at one
time. The key in your situation is to do the updates in smaller batches.
Andrew J. Kelly
SQL Server MVP
"Kevin" <anonymous@.discussions.microsoft.com> wrote in message
news:4A65CF81-2DD6-4F53-AA7A-E7B00FF50CE2@.microsoft.com...
quote:

> Thanks for your response.
> Does the frequency of log checkpoints significantly slow down a long

running update statement? Should I create a large transaction log that will
not need to dynamically grow and set the recovery interval to a high value
so that the frequency of checkpoints is reduced?
quote:

> thanks,
> Kevin

Monday, March 26, 2012

optimizer shows high record count

We recently have found a query that started to run long (30 seconds as
opposed to <1). No significant change in data, statistics updated,
etc. SQLServer 2000 sp3
When looking at the rowcount on one of the execution plan tasks it
shows >9 million rows, the table only has 14K rows in it.
We've done dbcc on the table/indexes with no results/corruption. In
our development environment, this works as expected, that is the row
count matches the estimated row count.
Any thoughts?
Thanks in advance.
Jason
Have you updated the statistics or reindexed that table lately?
Andrew J. Kelly SQL MVP
"fc_celtic_fan" <jasonb@.brandes.com> wrote in message
news:1107996642.783750.242070@.g14g2000cwa.googlegr oups.com...
> We recently have found a query that started to run long (30 seconds as
> opposed to <1). No significant change in data, statistics updated,
> etc. SQLServer 2000 sp3
> When looking at the rowcount on one of the execution plan tasks it
> shows >9 million rows, the table only has 14K rows in it.
> We've done dbcc on the table/indexes with no results/corruption. In
> our development environment, this works as expected, that is the row
> count matches the estimated row count.
> Any thoughts?
> Thanks in advance.
> Jason
>
|||Yes we have been in the boat as well and we used to run DBCC
updateusage('dbname','tablename')
"Andrew J. Kelly" <sqlmvpnooospam@.shadhawk.com> wrote in message
news:O1xTABxDFHA.2676@.TK2MSFTNGP12.phx.gbl...
> Have you updated the statistics or reindexed that table lately?
> --
> Andrew J. Kelly SQL MVP
>
> "fc_celtic_fan" <jasonb@.brandes.com> wrote in message
> news:1107996642.783750.242070@.g14g2000cwa.googlegr oups.com...
>
|||What does sysindexes say? Also, did you do UPDATEUSAGE with ROW_COUNT?
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
http://www.sqlug.se/
"Hassan" <fatima_ja@.hotmail.com> wrote in message news:Owi8xM0DFHA.3596@.TK2MSFTNGP10.phx.gbl...
> Yes we have been in the boat as well and we used to run DBCC
> updateusage('dbname','tablename')
> "Andrew J. Kelly" <sqlmvpnooospam@.shadhawk.com> wrote in message
> news:O1xTABxDFHA.2676@.TK2MSFTNGP12.phx.gbl...
>

optimizer shows high record count

We recently have found a query that started to run long (30 seconds as
opposed to <1). No significant change in data, statistics updated,
etc. SQLServer 2000 sp3
When looking at the rowcount on one of the execution plan tasks it
shows >9 million rows, the table only has 14K rows in it.
We've done dbcc on the table/indexes with no results/corruption. In
our development environment, this works as expected, that is the row
count matches the estimated row count.
Any thoughts?
Thanks in advance.
JasonHave you updated the statistics or reindexed that table lately?
Andrew J. Kelly SQL MVP
"fc_celtic_fan" <jasonb@.brandes.com> wrote in message
news:1107996642.783750.242070@.g14g2000cwa.googlegroups.com...
> We recently have found a query that started to run long (30 seconds as
> opposed to <1). No significant change in data, statistics updated,
> etc. SQLServer 2000 sp3
> When looking at the rowcount on one of the execution plan tasks it
> shows >9 million rows, the table only has 14K rows in it.
> We've done dbcc on the table/indexes with no results/corruption. In
> our development environment, this works as expected, that is the row
> count matches the estimated row count.
> Any thoughts?
> Thanks in advance.
> Jason
>|||Yes we have been in the boat as well and we used to run DBCC
updateusage('dbname','tablename')
"Andrew J. Kelly" <sqlmvpnooospam@.shadhawk.com> wrote in message
news:O1xTABxDFHA.2676@.TK2MSFTNGP12.phx.gbl...
> Have you updated the statistics or reindexed that table lately?
> --
> Andrew J. Kelly SQL MVP
>
> "fc_celtic_fan" <jasonb@.brandes.com> wrote in message
> news:1107996642.783750.242070@.g14g2000cwa.googlegroups.com...
>|||What does sysindexes say? Also, did you do UPDATEUSAGE with ROW_COUNT?
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
http://www.sqlug.se/
"Hassan" <fatima_ja@.hotmail.com> wrote in message news:Owi8xM0DFHA.3596@.TK2MSFTNGP10.phx.gbl
..
> Yes we have been in the boat as well and we used to run DBCC
> updateusage('dbname','tablename')
> "Andrew J. Kelly" <sqlmvpnooospam@.shadhawk.com> wrote in message
> news:O1xTABxDFHA.2676@.TK2MSFTNGP12.phx.gbl...
>sql

optimizer shows high record count

We recently have found a query that started to run long (30 seconds as
opposed to <1). No significant change in data, statistics updated,
etc. SQLServer 2000 sp3
When looking at the rowcount on one of the execution plan tasks it
shows >9 million rows, the table only has 14K rows in it.
We've done dbcc on the table/indexes with no results/corruption. In
our development environment, this works as expected, that is the row
count matches the estimated row count.
Any thoughts?
Thanks in advance.
JasonHave you updated the statistics or reindexed that table lately?
--
Andrew J. Kelly SQL MVP
"fc_celtic_fan" <jasonb@.brandes.com> wrote in message
news:1107996642.783750.242070@.g14g2000cwa.googlegroups.com...
> We recently have found a query that started to run long (30 seconds as
> opposed to <1). No significant change in data, statistics updated,
> etc. SQLServer 2000 sp3
> When looking at the rowcount on one of the execution plan tasks it
> shows >9 million rows, the table only has 14K rows in it.
> We've done dbcc on the table/indexes with no results/corruption. In
> our development environment, this works as expected, that is the row
> count matches the estimated row count.
> Any thoughts?
> Thanks in advance.
> Jason
>|||Yes we have been in the boat as well and we used to run DBCC
updateusage('dbname','tablename')
"Andrew J. Kelly" <sqlmvpnooospam@.shadhawk.com> wrote in message
news:O1xTABxDFHA.2676@.TK2MSFTNGP12.phx.gbl...
> Have you updated the statistics or reindexed that table lately?
> --
> Andrew J. Kelly SQL MVP
>
> "fc_celtic_fan" <jasonb@.brandes.com> wrote in message
> news:1107996642.783750.242070@.g14g2000cwa.googlegroups.com...
> >
> > We recently have found a query that started to run long (30 seconds as
> > opposed to <1). No significant change in data, statistics updated,
> > etc. SQLServer 2000 sp3
> >
> > When looking at the rowcount on one of the execution plan tasks it
> > shows >9 million rows, the table only has 14K rows in it.
> >
> > We've done dbcc on the table/indexes with no results/corruption. In
> > our development environment, this works as expected, that is the row
> > count matches the estimated row count.
> >
> > Any thoughts?
> >
> > Thanks in advance.
> >
> > Jason
> >
>|||What does sysindexes say? Also, did you do UPDATEUSAGE with ROW_COUNT?
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
http://www.sqlug.se/
"Hassan" <fatima_ja@.hotmail.com> wrote in message news:Owi8xM0DFHA.3596@.TK2MSFTNGP10.phx.gbl...
> Yes we have been in the boat as well and we used to run DBCC
> updateusage('dbname','tablename')
> "Andrew J. Kelly" <sqlmvpnooospam@.shadhawk.com> wrote in message
> news:O1xTABxDFHA.2676@.TK2MSFTNGP12.phx.gbl...
>> Have you updated the statistics or reindexed that table lately?
>> --
>> Andrew J. Kelly SQL MVP
>>
>> "fc_celtic_fan" <jasonb@.brandes.com> wrote in message
>> news:1107996642.783750.242070@.g14g2000cwa.googlegroups.com...
>> >
>> > We recently have found a query that started to run long (30 seconds as
>> > opposed to <1). No significant change in data, statistics updated,
>> > etc. SQLServer 2000 sp3
>> >
>> > When looking at the rowcount on one of the execution plan tasks it
>> > shows >9 million rows, the table only has 14K rows in it.
>> >
>> > We've done dbcc on the table/indexes with no results/corruption. In
>> > our development environment, this works as expected, that is the row
>> > count matches the estimated row count.
>> >
>> > Any thoughts?
>> >
>> > Thanks in advance.
>> >
>> > Jason
>> >
>>
>

Monday, March 19, 2012

Optimising Select statements which has a LIKE where clause.

Hi all

I have been doing some development work in a large VB6 application. I have updated the search capabilities of the application to allow the user to search on partial addresses as the existing search routine only allowed you to search on the whole line of the address.

Simple change to the stored procedure (this is just an example not the real stored proc):

From:
Select Top 3000 * from TL_ClientAddresses with(nolock) Where strPostCode = W1 ABC
To:
Select Top 3000 * from TL_ClientAddresses with(nolock) Where strPostCode LIKE W1%

Now this is when things went a bit crazy. I know the implications of using with(nolock). But seeing the code is only using the ID field to get the required row, and the database is a live database with hundreds of users at any one time (some updating), I think a dirty read is ok in this routine, as I dont want SQL to create a shared lock.

Anyway my problem is this. After the change, the search now created a Shared Lock which sometimes locks out some of the live users updating the system. The Select is also extremely SLOW. It took about 5 minutes to search just over a million records (locking the database during the search, and giving my manager good reason to shout abuse at me). So I checked the indexes. I had an index set on:

strAddressLine1, strAddressLine2, strAddressLine3, strAddressLine4, strPostCode.

So I created an index just for the strPostCode (non clustered).

This had no change to the Like select what so ever. So I am now stuck.

1) Is there another way to search for part of a text field in SQL.
2) Does Like comparison use the index in any way? If so how do I set this index up?
3) Can I stop a Shared Lock being created when I do a like select?
4) Do you have any good comebacks I could tell the boss after his next outburst of abuse (please not so bad that he sacks me).

Any advice truly appreciated.1. I have been working on smaller database systems the last couple of years but as for number 1 try changing the query to "=" with a wild card "%" in the QA with the show execution plan on and see if the index is being used.

2. I seem to remember that the like operator cancels the index. To check this I would execute the query in the QA and check the execution plan.

3. Don't know off the top of my head.

4. Tell your boss that software like the people who create it are imperfect things.|||Like is one of those "fuzzy" things and does not use indexes. Postcodes are notoriously difficult to search on...

In your example you give "W1%"

realise that this will return W12 etc

I in the time I had to do this tried to Narrow the user down to the local as in W1
W12 etc

Alternative prospect here

Split your Postcode into two fields (I know it sounds wierd) but then you can do an = rather than a like and an index can be used!|||I'd try to run the query in the Query Analyzer. In the form that you posted the query, it ought to use the PostCode index. It ought to be able to ride the index as far as the first wildcard (percent sign in this case). If you examine the query plan, it might give you some idea of where the problem is.

-PatP|||I get an index seek with a bookmark lookup

USE Northwind
GO

SET NOCOUNT ON
CREATE TABLE myTable99(strPostCode varchar(10), Col2 int)
GO

INSERT INTO myTable99(strPostCode, Col2)
SELECT 'W1Me',1 UNION ALL
SELECT 'W2Me',2 UNION ALL
SELECT 'W3Me',3 UNION ALL
SELECT 'W4Me',4
GO

CREATE INDEX myTable99_strPostCode ON myTable99(strPostCode)
GO

--[CTRL]+K
Select Top 3000 * from myTable99 with(nolock) Where strPostCode LIKE 'W1%'
GO

SET NOCOUNT OFF
GO|||Yeah, but that's using the code that they posted, which might or might not generate the same plan as the code they are actually using ;) Not that I've ever been burned by different code being posted than what is actually run before, I just read about it in this book once...

-PatP|||First like to thank everyone who replied. Very much appreciated.

Unfortunately I am still not much closer at finding a solution. I have done the execution plan thing although I can see a index seek, I dont think the index I have created is being used (but I am not sure).

If I delete the index, then the search time on about 500,000 records (Im testing from a subset of the total number of rows in the table) is about the same as when the index is present. If I do a = search, then with an index runs in less than a second and without takes much longer.

Anyway if anyone has any other ideas or a total different approach I can take then please let me know. Also if anyone knows of any websites or books that look into like selects more deeply than just giving you the syntax, like every book and site I have found, then that would be good too.

Regards

Eamon.|||1. Try use index hint:
Select Top 3000 * from TL_ClientAddresses with(nolock, INDEX (your_index_name)) Where strPostCode LIKE W1%
2. Try update statistics:
EXEC sp_updatestats
3. Try change query:
Select Top 3000 * from TL_ClientAddresses with(nolock)
Where strPostCode >= W1 AND strPostCode =< W1z
4. If your query fetch more then 20% table then optimizer don't use index|||mwolf! Your a Star!!!

Select Top 3000 * from TL_ClientAddresses with(nolock, INDEX (your_index_name)) Where strPostCode LIKE W1%

Works a treat!!! Gone from over a minute down to 6 seconds just by adding the 'INDEX()' statement.

I think that's the answer to my problem, Thankyou very much!!!

Regards

Eamon.

Monday, March 12, 2012

Optimal solution for getting timestamp of last entry

Hi

I'm trying to find the optimal way of getting the timestamp of the last updated entry in an mssql database. A database is updated only about 5 times a minute, how ever a request for the time of the last entry could be around 1 per second. For this reason i was thinking of having a separate table which has a single row which is updated everytime a new entry is updated in the main table. I would then only need a simple SELECT statement and need very little processing power.

Is this the best method, or can you think of any others i could use?

many thanksWhat's the scope? Database wide or table specific?|||single table, single row? a potential bottleneck, but only 5/minute should be no problem, so yeah, that would be the simplest solution

but if this is just for your main table, consider an index on the datetime column descending, so that TOP 1 gets your last update easily|||but if this is just for your main table, consider an index on the datetime column descending, so that TOP 1 gets your last update easilyHow does SQL Server handle a monotonically decreasing index? Presumably with regular page splits? Like you say low activity will mitigate this somewhat.|||oh dear, i'm in over my head here

what is monotonically? no music? and how is monotonically different from sequentially? from consecutively?

and what's a page split?

sheesh, i should stick to stuff i know|||SELECT MAX(upd_dt) FROM (
SELECT MAX(upd_dt) AS upd_dt FROM tbl1 UNION ALL
SELECT MAX(upd_dt) AS upd_dt FROM tbl2 UNION ALL
SELECT MAX(upd_dt) AS upd_dt FROM tbl3 UNION ALL
SELECT MAX(upd_dt) AS upd_dt FROM tbl4 UNION ALL
SELECT MAX(upd_dt) AS upd_dt FROM tbl5 UNION ALL
SELECT MAX(upd_dt) AS upd_dt FROM tbl6) AS XXX

???????????????

You gotta give us more to go on|||Hi, its a pretty simple database, there are only two tables, one with all the data, and the other which will hold the single row with the latest time stamp.

I realise i can SELECT the top1 descending record from the main table, but won't that be more work than simply selecting a single value?

...or is selecting top1 more viable than loosing out on 'bottle necking' when selecting a single row..!|||more work? for you or for the server?

i'll bet if you timed the cpu cycles, it'd be pretty close|||more work? for you or for the server?

i'll bet if you timed the cpu cycles, it'd be pretty close

lol - i don't mind doing the work! - i just want this to be as optimal as possible...|||How many rows in the table?|||oh dear, i'm in over my head here
...
sheesh, i should stick to stuff i knowI don't think so - I think you just sometimes pretend you know less than you do so no one asks you anything remotely resembling a dba question :)|||In the main table, there will be approximately 1000 new rows per day.

I suppose this leads onto another question, are there any limits other than disk space, eg on the cpu that i should be aware of?|||Sorry I meant in total|||well theres zero rows at the moment because im in the middle of building the application and setting up the database. But i am expecting approx 1000 new rows a day - not sure what limits are advisable as to how many rows before i need to do something, eg create a new table or whatever?|||well theres zero rows at the moment because im in the middle of building the application and setting up the database. But i am expecting approx 1000 new rows a day - not sure what limits are advisable as to how many rows before i need to do something, eg create a new table or whatever?You won't get close to the sort of volume where you need to start getting canny at 1000 inserts a day.

Agreed with Rudy - just put the column in your table and then select MAX() of that column to get the last update. Index the column. I think I would index ASC but there you go. Triger to update it.

BTW - one table - is it normalised?|||ok - sounds good to me - can i just write this out how i see it working from what you've said above:

1) Index time/date column Ascending
2) When getting the last update, use something similiar to:

SELECT MAX(timeDateStampColumn) as "LastEntry"
FROM table;

BTW - one table - is it normalised?
My application is based around sms text messages, each new row in my table is basically a new text message, there are only a few columns (id, message, mobile number, dateTimeStamp) so no need to normalise. I'm at the designing stages of the project so will certainly be more tables added later on.|||My application is based around sms text messages, each new row in my table is basically a new text message, there are only a few columns (id, message, mobile number, dateTimeStamp) so no need to normalise. That table structure sounds fine although I would disagree and say that the very early stages are absolutely the right time to normalise. I would also strongly recommend you design your complete database before worrying about requirements like "how do I find the time of the last SMS?".|||point taken ;)

thanks everyone for your excellent help (as usual) :D

Monday, February 20, 2012

OPENXML Question

How do I return the number of rows inserted/updated using OPENXML?
I tried to use the @.@.ROWCOUNT function, but it always returns a 0.
Generic update example trying to return the # of rows updated:
declare @.i int
exec sp_xml_preparedocument @.i output,
'<mydata>
<test xmlID="3" xmlData="blah blah blah"/>
<test xmlID="1" xmlData="blah"/>
</mydata>'
update test
set test.xmlData = ox.xmlData
from OpenXml(@.i, 'mydata/test')
with (xmlID int, xmlData nvarchar(30)) ox
where test.xmlID = ox.xmlID
RETURN @.@.ROWCOUNT --Returns a 0
exec sp_xml_removedocument @.i
Thanks,It will return the rowcount.
Can you check if the data was really updated.
I think its the data problem.
Or try using print @.@.rowcount as see.
"Robert" wrote:

> How do I return the number of rows inserted/updated using OPENXML?
> I tried to use the @.@.ROWCOUNT function, but it always returns a 0.
> Generic update example trying to return the # of rows updated:
> declare @.i int
> exec sp_xml_preparedocument @.i output,
> '<mydata>
> <test xmlID="3" xmlData="blah blah blah"/>
> <test xmlID="1" xmlData="blah"/>
> </mydata>'
> update test
> set test.xmlData = ox.xmlData
> from OpenXml(@.i, 'mydata/test')
> with (xmlID int, xmlData nvarchar(30)) ox
> where test.xmlID = ox.xmlID
> RETURN @.@.ROWCOUNT --Returns a 0
> exec sp_xml_removedocument @.i
>
> Thanks,
>|||Check my procedure here:
It works for me (rowcount stuff that is)
if exists (select * from sysobjects
where id = object_id('uspTitleUpdate') and sysstat & 0xf = 4)
drop procedure uspTitleUpdate
GO
CREATE PROCEDURE dbo.uspTitleUpdate (
@.xml_doc TEXT ,
@.numberRowsAffected int output --return
)
AS
SET NOCOUNT ON
DECLARE @.hdoc INT -- handle to XML doc
DECLARE @.errorTracker int -- used to "remember" the @.@.ERROR
DECLARE @.updateRowCount int
DECLARE @.insertRowCount int
--Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @.hdoc OUTPUT, @.XML_Doc
-- build a table (variable table) to store the xml-based result set
DECLARE @.titleupdate TABLE (
identityid int IDENTITY (1,1) ,
title_id varchar(6) ,
title varchar(80) ,
type varchar(32) ,
pub_id varchar(32) ,
price money ,
advance money ,
royalty varchar(32) ,
ytd_sales varchar(32) ,
notes TEXT ,
pubdate datetime ,
--used to differeniate between existing (update) and new ones (insert)
alreadyExists bit DEFAULT 0
)
--the next call will take the info IN the @.hdoc(with is the holder for
@.xml_doc), and put it IN a variableTable
INSERT @.titleupdate
(
title_id ,
title ,
type ,
pub_id ,
price ,
advance ,
royalty ,
ytd_sales ,
notes ,
pubdate ,
alreadyExists
)
SELECT
title_id ,
title ,
type ,
pub_id ,
price ,
advance ,
royalty ,
ytd_sales ,
notes ,
dbo.udf_convert_xml_date_to_datetime (pubdate) ,
0
FROM
-- use the correct XPath .. the second arg ("2" here) distinquishes
-- between textnode or an attribute, most times with
--.NET typed datasets, its a "2"
--This xpath MUST match the syntax of the DataSet
OPENXML (@.hdoc, '/TitlesDS/Titles', 2) WITH (
title_id varchar(6) ,
title varchar(80) ,
type varchar(32) ,
pub_id varchar(32) ,
price money ,
advance money ,
royalty varchar(32) ,
ytd_sales varchar(32) ,
notes TEXT ,
pubdate varchar(32) ,
alreadyExists bit
)
--select * from @.titleupdate
--lets differeniate between existing (update) and new ones (insert)
Update @.titleupdate
SET
alreadyExists = 1
FROM
@.titleupdate tu , titles
WHERE
--this where clause is a little weird, usually you'll must match
--primary key (int or global identifiers)
ltrim(rtrim(upper(titles.title_id))) = ltrim(rtrim(upper(tu.title_id)))
SET NOCOUNT OFF
Update
titles
set
title = tu.title ,
type = tu.type ,
pub_id = tu.pub_id ,
price = tu.price ,
advance = tu.advance ,
royalty = tu.royalty ,
ytd_sales = tu.ytd_sales ,
notes = tu.notes ,
pubdate = tu.pubdate
FROM
@.titleupdate tu , titles
WHERE
ltrim(rtrim(upper(titles.title_id))) = ltrim(rtrim(upper(tu.title_id)))
AND
tu.alreadyExists <> 0
Select @.updateRowCount = @.@.ROWCOUNT
INSERT INTO titles
(
title_id ,
title ,
type ,
pub_id ,
price ,
advance ,
royalty ,
ytd_sales ,
notes ,
pubdate
)
Select
title_id ,
title ,
type ,
pub_id ,
price ,
advance ,
royalty ,
ytd_sales ,
notes ,
pubdate
FROM
@.titleupdate
WHERE
alreadyExists = 0
Select @.insertRowCount = @.@.ROWCOUNT
select @.numberRowsAffected = @.insertRowCount + @.updateRowCount
--select * from titles
SET NOCOUNT OFF
GO
"Robert" <Robert@.discussions.microsoft.com> wrote in message
news:3C2C4124-DEE9-4A0E-82CE-FE91CCFDC5AF@.microsoft.com...
> How do I return the number of rows inserted/updated using OPENXML?
> I tried to use the @.@.ROWCOUNT function, but it always returns a 0.
> Generic update example trying to return the # of rows updated:
> declare @.i int
> exec sp_xml_preparedocument @.i output,
> '<mydata>
> <test xmlID="3" xmlData="blah blah blah"/>
> <test xmlID="1" xmlData="blah"/>
> </mydata>'
> update test
> set test.xmlData = ox.xmlData
> from OpenXml(@.i, 'mydata/test')
> with (xmlID int, xmlData nvarchar(30)) ox
> where test.xmlID = ox.xmlID
> RETURN @.@.ROWCOUNT --Returns a 0
> exec sp_xml_removedocument @.i
>
> Thanks,
>