简体   繁体   中英

Insert into tables values not contained in another

i'm trying to insert data into one table from another

INSERT INTO test(CRED_NUMERO, GRP_NUMERO, ARE_NUMERO, CRACTI_NUMERO, CRAC_DIFPORGRUPO, 
JORN_NUMERO, TURN_NUMERO, CRAC_QTDTOTALACESSOS, CRAC_QTDACESSOS, CRAC_VERFSENHA, 
CRAC_VERFDIGITAL, CRAC_ULTPASSAGEM, CRAC_ULTPASSAGEMPONTO)
VALUES ((SELECT PES_NUMERO FROM PESSOAS WHERE PES_NUMERO NOT IN (SELECT CRED_NUMERO 
FROM CRED_ACESSO)),'1', '1', '1', NULL,NULL,NULL,'999', '0', '0', '0',
'2016-08-20 20:02:00.000','2000-01-01 00:00:00.000')

However when running the query the following error is shown

"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."

I have read previous questions regarding the same error and it is suggested to use "IN" instead of "=", however, the select query has a NOT IN. Could you please help me with this? Thanks in advance.

Instead of insert . . . values insert . . . values insert . . . values , using insert . . select insert . . select insert . . select :

INSERT . . .
    SELECT PES_NUMERO, ,'1', '1', '1', NULL, NULL, NULL, '999', '0', '0', '0',
           '2016-08-20 20:02:00.000', '2000-01-01 00:00:00.000'
    FROM PESSOAS
    WHERE PES_NUMERO NOT IN (SELECT CRED_NUMERO FROM CRED_ACESSO);

Note: I strongly advise you to use NOT EXISTS rather than NOT IN . NOT IN returns no rows if CRED_NUMERO is ever NULL . The following is just a good habit, so you don't ever have this problem:

INSERT . . .
    SELECT pPES_NUMERO, ,'1', '1', '1', NULL, NULL, NULL, '999', '0', '0', '0',
           '2016-08-20 20:02:00.000', '2000-01-01 00:00:00.000'
    FROM PESSOAS p
    WHERE NOT EXISTS (SELECT 1 CRED_ACESSO ca WHERE p.PES_NUMERO = ca.CRED_NUMERO);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM