Question

I'm trying to use data stored in a temporary result set (SOURCE in the code) to fill another table with SQL Server 2012. When executing the below code I get the error "The multi-part identifier "SOURCE.JnlDetoaId" could not be bound".

SELECT Journaldet.*, Agency.ID_Agency INTO SOURCE
FROM Journaldet 
inner join Agency 
ON Agency.Agency_ID = Journaldet.AgenceId

IF  ((SELECT COUNT(Journal.Journal_ID) FROM dbo.Journal, SOURCE WHERE Journal_ID =      SOURCE.JournalId)=0)
INSERT INTO Discarded.JournalDet(JournalDet_ID, Amount, Sensoa, DetoaId,    ID_Agency, JournalId, Appli_Source, ReasonDiscarded, DateDiscarded) 
VALUES (SOURCE.JnlDetoaId, SOURCE.Amount, SOURCE.Sensoa, SOURCE.DetoaId,    SOURCE.ID_Agency, JournalId, 'GameApps','Member not yet inserted', GETDATE());

I read some threads about here but didn't see how to apply them to my case. Any help please?

Was it helpful?

Solution 2

Below is how I solved my issue. The SOURCE was not seen in the INSERT as a result set as I wanted. It was nothing for the INSERT. I just rewrote the queries in such a way that the result set be seen in the INSERT. Thanks a lot user2919277.

INSERT INTO  Discarded.JournalDet 
(JournalDet_ID, Amount, Sensoa, DetoaId, ID_Agency, JournalId, Appli_Source,      ReasonDiscarded, DateDiscarded)
SELECT SOURCE1.JnlDetoaId, Amount,Sensoa,DetoaId,ID_Agency,JournalId, 'GameApps', 'Member not yet inserted', GETDATE() 
FROM Journaldet  AS SOURCE1 
inner join Agency AS SOURCE2 ON SOURCE2.Agency_ID = SOURCE1.AgenceId
WHERE  ((SELECT COUNT(Journal.Journal_ID) FROM dbo.Journal WHERE dbo.Journal.Journal_ID = SOURCE1.JournalId)=0)

OTHER TIPS

SELECT Journaldet.*, Agency.ID_Agency INTO sourceTable
FROM Journaldet 
inner join Agency 
ON Agency.Agency_ID = Journaldet.AgenceId;

IF ((SELECT COUNT(j.Journal_ID) FROM dbo.Journal as j, sourceTable s WHERE j.Journal_ID = s.JournalId) = 0)
    INSERT INTO Discarded.JournalDet(JournalDet_ID, Amount, Sensoa, DetoaId,ID_Agency, JournalId, Appli_Source, ReasonDiscarded, DateDiscarded) 
    VALUES (select JnlDetoaId, Amount, Sensoa, DetoaId,  ID_Agency, JournalId, 'GameApps','Member not yet inserted', GETDATE() FROM sourceTable)

The problem was in you insert () values(). To insert values into your Discarded.JournalDet table. You cannot just use the above fields from source table. You have to select from the source table.

U cannot just user the source.JournalDet .. and soo on , directly only because they are defined few line above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top