I'm having a problem inserting data into a table from a temporary table. Basically, I have a temporary table called TEMPADDU25 which contains two columns called SERIALNUMBER and MAILINGTYPE.
I need to get the contents of TEMPADDU25.MAILINGTYPE and insert it into MAILINGPREFERENCE.MAILINGTYPE
I'm using the following SQL script, but am receiving the error:
Cannot insert the value NULL into column 'SERIALNUMBER', table 'dbo.MAILINGPREFERENCE'; column does not allow nulls. INSERT fails.
My SQL script:
INSERT INTO mailingpreference (mailingtype)
SELECT mailingtype
FROM tempaddu25
WHERE serialnumber=TEMPADDU25.serialnumber .
Thank you once again. I can see how the script should work but I'm now getting this error:
Violation of PRIMARY KEY constraint 'PK_MAILINGPREFERENCE'. Cannot insert duplicate key in object 'dbo.MAILINGPREFERENCE'.
The MAILINGPREFERENCE table does contain other columns that aren't in the TEMPADDU25 table. These columns should all be NULL. I'm unsure if that is significant.
Both SERIALNUMBER and MAILINGTYPE are Primary Keys on the table.I can add multiple MAILINGTYPE entries via the actual database, but can't work out how to do this in SQL.
INSERT INTO mailingpreference (mailingtype,serialnumber)
SELECT DISTINCT
a.mailingtype
,a.serialnumber
FROM tempaddu25 as a
WHERE a.serialnumber is not null
AND NOT EXISTS(SELECT 1
FROM mailingpreference as b
WHERE a.mailingtype=a.mailingtype
AND b.serialnumber=a.serialnumber
)