0

I want a basic update procedure that updates a temporary table and orders it by PrimID and myDates, and then updates a permanent table. The data structure looks like this:

PrimID  MyDates     Price
1       1/1/2014    1
1       1/2/2014    2
2       1/1/2014    11
2       1/2/2014    12
3       1/1/2014    21
3       1/2/2014    22

The csv file looks exactly the same, just without the header column names. Here is my code thus far:

CREATE Table #TempT
(
   PrimID Int,
   myDate Date,
   myPrice Float
);

BULK
INSERT #TempT
FROM 'D:\MyWerk\SQL\TEST_dPrice_Data.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)


Select * From #TempT
Order by PrimID,myDate

Drop Table #TempT

What is missing, and what I am trying to get to, is the UPDATE of the permanent table with the ordered #TempT, ordered by PrimID and then myDates(oldest to lastest). If there are PrimID & myDates data in the csv that are already in the permanent table, I want to overwrite the data in the permanent file as well. Also, is there a better way to get the data in chronological order, other than using order by?

I use SQL Server 2012.

Much appreciated.

2
  • I'm having a hard time understanding what you're after, you want to update the mydate and myprice values based on the primid, but only on price if primid and mydate are in both tables? Commented Sep 18, 2014 at 19:18
  • An order by clause is rarely if ever necessary in an update query. Depending on what you are trying to achieve, maybe the sql max() function is appropriate. Commented Sep 18, 2014 at 19:37

1 Answer 1

2

Don't try to store your data in SQL tables in some kind of row order -- this is inefficient. You can sort when you query the data.

As for the insert/update behavior, a SQL merge does this quite well. After your Bulk Insert, you can execute something like this:

MERGE PermanentT AS [TARGET]
USING #TempT AS [SOURCE]
ON [TARGET].PrimId = [SOURCE].PrimId
    AND [TARGET].MyDates = [SOURCE].MyDates
WHEN MATCHED AND [TARGET].PRICE <> [SOURCE].PRICE
THEN UPDATE SET [TARGET].PRICE = [SOURCE].PRICE
WHEN NOT MATCHED
THEN INSERT (PrimID, myDate, myPrice) 
VALUES (SOURCE.PrimID, SOURCE.myDate, SOURCE.myPrice);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Greenspark, seems exactly what I need. One thing, I get "Incorrect syntax near [TARGET]." At your row, "WHEN NOT MATCHED BY [TARGET]" ?
Oops. yeah, we don't need the "By [TARGET]" there. Also, the whole merge statement needs to end in a semi colon. I've made those changes above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.