2012年3月19日星期一

Fixing a slow, brute force set of SQL calls

I've got a huge inefficiency in my code that I'm trying to fix. I'm coding in VB.NET using ASP.NET and an MSSQL 2000 server.

I'm working in a temporary table that has an identical layout as another, non-temporary table in my database. Once I get the temp table how I want it, I need to insert everything from that table into my main table. Before I can do that, however, I need to delete all the records in the main table with certain fields that match a record's fields in the temporary table.

Right now, I have a method that builds one delete statement per record in the temporary table and then runs those statements on the main table. Since I'm dealing with the order of 50,000 records (at least) here, building and sending those statements to the server takes forever.

Is there a way I can accomplish the same thing without building and sending such a huge SQL call to the server? If so, how would I go about doing that?

Thanks in advance for whatever help you can give,
-StarwizMy suggestions would be to use this sort of SQL command:


DELETE
FROM
myTable
INNER JOIN
#myTempTable ON #myTempTable.column1 = myTable.column1 <etc>

Terri|||Wouldn't this delete the records from the temporary table, too?|||No, the FROM clause specifies the table to use for the DELETE statement. Only the records from myTable matching the JOIN condition will be deleted.

Terri|||Okay then...but I can't even run it to see, since I get an error:

With the statement:
Delete from PPC inner join PPCTemp on PPC.searchengine = PPCTemp.searchengine and PPC.[date] = PPCTemp.[date] and PPC.keyword = PPCTemp.keyword

I get the error:
ERROR [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'inner'.

Any ideas?|||That's because I gave you the wrong syntax and somewhat incorrect information ;-) The table name also has to follow the DELETE statement, and the table name following the DELETE is the one from which records are deleted:


Delete PPC from PPC inner join PPCTemp on PPC.searchengine = PPCTemp.searchengine and PPC.[date] = PPCTemp.[date] and PPC.keyword = PPCTemp.keyword

You should check out the DELETE topic in SQL Server Books Online for more background information on this topic.

Terri|||With the right syntax, it works great (lol)...a million times faster, too!

Thanks a lot.

没有评论:

发表评论