Click here to Skip to main content
15,884,838 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I am facing an issue whil trying to insert values into a temp table using not exists.

Below is the dummy table that i created:

CREATE TABLE TEST_DEL(ID INT, NAME VARCHAR(10))


dummy inserts:

INSERT INTO TEST_DEL VALUES(1, 'A')
INSERT INTO TEST_DEL VALUES(2, 'B')
INSERT INTO TEST_DEL VALUES(2, 'C')
INSERT INTO TEST_DEL VALUES(3, 'D')
INSERT INTO TEST_DEL VALUES(4, 'E')


creating a temp table structure to get one record for each 'ID' value from Test_DEL table:

SELECT * INTO #TEMP FROM TEST_DEL WHERE 1=0


i prepared the following query to insert one record into temp table for each id from Test_DEL:

INSERT INTO #TEMP (ID, NAME)
SELECT  a.ID, a.NAME FROM TEST_DEL A 
WHERE NOT EXISTS(SELECT 1 FROM #TEMP B WHERE B.ID = A.ID


here my expectation with this query is to check for each record with id value before inserting into temp table, if it doesn't exist already then insert, and if any record exists with ID value in temp table, skip that record from inserting.

I am supposed to get 4 records in to #temp bu i am getting all the 5 records.

can anyone please suggest whats wrong in the query that i wrote?

Thanks in advance.

What I have tried:

Tried the above insert statement with "not exists" but it isn't working.
Posted
Updated 6-Nov-17 21:03pm
Comments
pt1401 7-Nov-17 2:50am    
Why do you think you should only get 4 records?
SELECT * INTO #TEMP FROM TEST_DEL WHERE 1=0 inserts nothing, it just creates an empty temp table with the correct schema.

1 solution

Ah ok, there are two instances to ID=2.

The reason you get all 5 is that ID=2 does not exist in the temp table before the insert statement (and remember you only have a single insert statement, not 4 or 5 individual ones).

Try running the SELECT on it's own:-
SELECT  a.Id, a.NAME FROM TEST_DEL A 
WHERE NOT EXISTS(SELECT 1 FROM #TEMP B WHERE B.Id = A.Id)

Id          NAME
----------- ----------
1           A
2           B
2           C
3           D
4           E

(5 row(s) affected)


You can think of the insert as a two-stage operation:-
1. SELECT all the rows in TEST_DEL that don't exist in the temp table.
2. INSERT those rows into the temp table.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900