SQL Query - is this correct?

SmashAndGrab
SmashAndGrab used Ask the Experts™
on
Hi,

I have the following SQL Query:


INSERT INTO Archive_E2LTORI SELECT * FROM E2LTORI WHERE LGNUM = '" & prRS("LGNUM") & "' AND TANUM = '" & prRS("TANUM") & "' AND VBELN ='" & Delivery & "' AND VBELN NOT IN(SELECT VBELN from Archive_E2LTORI where VBELN= '" & Delivery & "'

It basically copys data from the LIVE table to the arichive table.

The problem is that I kept getting a a primary key issue - so I then added the "NOT IN" so that the query makes sure that the combo exists before inserting.


My question is:

Is this correct?   Or should I add the addtional fields the the NOT IN part?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Vitor MontalvãoIT Engineer
Distinguished Expert 2017

Commented:
When archiving data you must assure that the data you're going to archive is not archived yet.
The NOT IN clause is just one of the many solutions that you have to achieve this.

Author

Commented:
I think the query should be ..


INSERT INTO Archive_E2LTORI SELECT * FROM E2LTORI WHERE LGNUM = '" & prRS("LGNUM") & "' AND TANUM = '" & prRS("TANUM") & "' AND VBELN ='" & Delivery & "' AND VBELN NOT IN(SELECT VBELN from Archive_E2LTORI LGNUM = '" & prRS("LGNUM") & "' AND TANUM = '" & prRS("TANUM") & "' AND VBELN ='" & Delivery & "')

I think?
IT Engineer
Distinguished Expert 2017
Commented:
Try with NOT EXISTS instead:
INSERT INTO Archive_E2LTORI 
SELECT * 
FROM E2LTORI 
WHERE LGNUM = '" & prRS("LGNUM") & "' AND TANUM = '" & prRS("TANUM") & "' AND VBELN ='" & Delivery & "' 
	AND NOT EXISTS (SELECT 1
			FROM Archive_E2LTORI a
			WHERE a.LGNUM = E2LTORI.LGNUM AND a.TANUM = E2LTORI.TANUM AND a.VBELN = E2LTORI.VBELN)

Open in new window

Chris LuttrellSenior Database Architect

Commented:
What is your primary key in the Archive_E2LTORI table?
What do you want to do if the record already exists, nothing, just do not insert again?  What if other columns have changed?
Select * is bad practice for production code, and not specifying the columns in the insert.  This will break if someone modifies either table on you.
Vitor MontalvãoIT Engineer
Distinguished Expert 2017

Commented:
SmashAndGrab, a feedback will be appreciated.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial