Mysql Stored procedure with cursor - mysql

Mysql cursor issue?
I have written a stored procedure which will travel's record from one table and insert those into 2-3 different tables
using insert statements.
Problem is that i am checking if record is not exists in table1 then I am inserting record from temptable to table1 ,table2 sequentially
,but the condition is having some problem i don't know it its always going into else part.
Code sample is as follows:
CREATE PROCEDURE `insertData`(In clientNo INT,In usedID INT)
BEGIN
declare mame varchar(100);
declare address varchar(100);
declare city varchar(50);
declare IdentityNO1 varchar(20)
declare cur1 cursor for select * from temptable;
declare continue handler for not found set done=1;
SET #clientNo = clientNO;
SET #userID = userID;
set done = 0;
open cur1;
igmLoop: loop
fetch cur1 into Name,Address,City,IdentityNO1,clientNo;
if done = 1 then leave igmLoop; end if;
//If no record exists in some records table1,table2.
IF ( (SELECT COUNT(*) FROM table1
WHERE IndentityNo=IdentityNo1
AND clientNo=#clientNo) < = 0)
INSERT INTO table1 (Name,IdentityNO) VALUES (name,IdentityNO1);
INSERT INTO table2 (Address,City) VALUES(address,city);
ELSE
INSERT INTO tblexceptional(Name,Address,City,IdentityNo)
VALUES(name,address,city,IdentityNo1);
end loop igmLoop;
close cur1;
END

There is no THEN nor END IF keywords, the procedure cannot compile.
Check this link for proper syntax of IF statement: http://dev.mysql.com/doc/refman/5.7/en/if.html
Use EXIST operator instead of (SELECT count(*)... ) <=0,
read this link to know the reason: http://sqlblog.com/blogs/andrew_kelly/archive/2007/12/15/exists-vs-count-the-battle-never-ends.aspx
IF EXISTS(
SELECT null FROM table1
WHERE IndentityNo=IdentityNo1
AND clientNo=#clientNo
)
THEN
INSERT INTO table1 (Name,IdentityNO) VALUES (name,IdentityNO1);
INSERT INTO table2 (Address,City) VALUES(address,city);
ELSE
INSERT INTO tblexceptional(Name,Address,City,IdentityNo)
VALUES(name,address,city,IdentityNo1);
END IF;
I recommend using some prefixes for procedure arguments and variable names to avoid ambiguity, for example use p_ for parameters and v_ for variables. It's hard to guess, looking at this code, which name is a column name, a variable or a procedure parameter. This can lead to mistakes and errors.
Avoid using SELECT * - this code will fail if someone will change the table structure. Explicitely list required columns in the cursor declaration:
declare cur1 cursor for
select name,Address,City,IdentityNO,clientNo
from temptable;
The corrected procedure might look like this:
CREATE PROCEDURE `insertData`(In p_clientNo INT,In p_usedID INT)
BEGIN
declare v_name varchar(100);
declare v_address varchar(100);
declare v_city varchar(50);
declare v_IdentityNO varchar(20)
declare v_clientNo int
declare cur1 cursor for
select name,Address,City,IdentityNO,clientNo
from temptable;
declare continue handler for not found set done=1;
set done = 0;
open cur1;
igmLoop: loop
fetch cur1 into v_name,v_Address,v_City,v_IdentityNO,v_clientNo;
if done = 1 then leave igmLoop; end if;
//If no record exists in some records table1,table2.
IF EXISTS( SELECT 1 FROM table1
WHERE IndentityNo = v_IdentityNo
AND clientNo = v_clientNo)
INSERT INTO table1 (Name,IdentityNO) VALUES (v_name,v_IdentityNO);
INSERT INTO table2 (Address,City) VALUES(v_address,v_city);
ELSE
INSERT INTO tblexceptional(Name,Address,City,IdentityNo)
VALUES(v_name,v_address,v_city,v_IdentityNo);
END IF;
end loop igmLoop;
close cur1;
END

Related

Select into multiple varibales with MySQL

I need to write a stored procedure using mysql.
In the repeat loop showing below, if I use something as:
SET VDATEI=(SELECT A.DATEI FROM STAFF_CONVENIOS A WHERE
A.CONV_ID=CONVE AND A.STAFF_ID=MED LIMIT 1);
the stored procedure works well and I get a result set.
But, I need select into multiple variables. Something as:
SELECT
A.DATEI, A.DIAI, A.HORAI
INTO
VDATEI, VDIAI, VHORAI
FROM
STAFF_CONVENIOS A
WHERE
A.CONV_ID = CONVE AND A.STAFF_ID = MED
LIMIT 1;
In this case my stored procedure is broken I get no result set.
How to use select into to multiple variables into stored procedure with temporary tables?
My stored procedure is similar to:
CREATE PROCEDURE P_GETHORARIOS(
IN `MED` BIGINT,
IN `DATAREF` DATE,
IN `ESPEC` BIGINT,
IN `CONVE` BIGINT
)
BEGIN
DECLARE BDONE,BTEMP, BOCUP INT;
DECLARE DIA;
DECLARE VDIA,OK TINYINT;
DECLARE VDURACAO TINYINT;
DECLARE VDATEI DATE;
DECLARE VDIAI TINYINT;
DECLARE VHORAI TIME;
DECLARE VHORA, VHORAI,VHORAF TIME;
DECLARE CURS CURSOR FOR SELECT DIA,COALESCE(A.DURACAO,30) AS DURACAO, A.HINI FROM STAFF_ESCALA A
WHERE A.DIA=DIA;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET BDONE = 1;
DROP TEMPORARY TABLE IF EXISTS TBLRESULTS;
CREATE TEMPORARY TABLE IF NOT EXISTS TBLRESULTS (
DATA_AG DATE,
DIA TINYINT,
HORA TIME );
SET DIA=DAYOFWEEK(DATAREF);
OPEN CURS;
SET BDONE = 0;
REPEAT
SET OK=TRUE;
FETCH CURS INTO VDIA,VDURACAO,VHORAI;
-- SET VDATEI=(SELECT A.DATEI FROM STAFF_CONVENIOS A WHERE A.CONV_ID=CONVE AND A.STAFF_ID=MED LIMIT 1);
SELECT A.DATEI, A.DIAI,A.HORAI INTO VDATEI, VDIAI,VHORAI FROM STAFF_CONVENIOS A WHERE A.CONV_ID=CONVE AND A.STAFF_ID=MED LIMIT 1;
SET BTEMP=IF(VDATEI IS NULL,TRUE,FALSE);
SET OK=OK AND BTEMP ;
IF (OK) THEN
INSERT INTO TBLRESULTS VALUES (DATAREF,VDIA,VHORA);
ELSE INSERT INTO TBLRESULTS VALUES (VDATEI,VDIAI,VHORAI);
END IF;
UNTIL BDONE END REPEAT;
CLOSE CURS;
SELECT A.* FROM TBLRESULTS;
END
I have posted a sample of my problem. Here is the real stored procedure:
CREATE DEFINER=`SYSDBA`#`%` PROCEDURE `P_GETHORARIOS`(
IN `MED` BIGINT,
IN `DATAREF` DATE,
IN `ESPEC` BIGINT,
IN `CONVE` BIGINT
)
LANGUAGE SQL
NOT DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE BDONE INT;
DECLARE BTEMP TINYINT;
DECLARE BOCUP TINYINT;
DECLARE DIA BIGINT;
DECLARE VDIA TINYINT;
DECLARE VDURACAO TINYINT;
DECLARE VHORA, VHORAI,VHORAF TIME;
DECLARE VMED_ID BIGINT;
DECLARE VESPEC_ID BIGINT;
DECLARE VCONV_ID BIGINT;
DECLARE OK TINYINT;
DECLARE VNOMEESPEC,VNOMEMED VARCHAR(100);
DECLARE CURS CURSOR FOR SELECT DIA,COALESCE(A.DURACAO,30) AS DURACAO, A.HINI, A.HFIM, A.STAFF_ID,B.NOME AS NOMESTAFF, A.ESPEC_ID,C.NOME AS NOMEESPEC
FROM STAFF_ESCALA A
LEFT JOIN STAFF B ON B.ID=A.STAFF_ID
LEFT JOIN ESPECIALIDADES C ON C.ID=A.ESPEC_ID
WHERE A.DIA=DIA;
-- DECLARE CURS CURSOR FOR SELECT HINI, HFIM FROM STAFF_ESCALA;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET BDONE = 1;
DROP TEMPORARY TABLE IF EXISTS TBLRESULTS;
CREATE TEMPORARY TABLE IF NOT EXISTS TBLRESULTS (
DATA_AG DATE,
DIA TINYINT,
HORA TIME,
MED_ID BIGINT,
NOME_MED VARCHAR(100),
ESPEC_ID BIGINT,
NOME_ESPEC VARCHAR(100)
);
SET DIA=DAYOFWEEK(DATAREF);
OPEN CURS;
SET BDONE = 0;
REPEAT
SET OK=TRUE;
FETCH CURS INTO VDIA,VDURACAO,VHORAI,VHORAF,VMED_ID,VNOMEMED,VESPEC_ID,VNOMEESPEC;
IF (MED IS NOT NULL) THEN
SET OK=IF(MED=VMED_ID,TRUE,FALSE) ;
END IF;
IF (ESPEC IS NOT NULL) THEN
SET OK=OK AND IF(ESPEC=VESPEC_ID,TRUE,FALSE) ;
END IF;
IF (CONVE IS NOT NULL) THEN
-- SET #EOK=(SELECT 1 FROM STAFF_CONVENIOS A WHERE A.CONV_ID=CONVE AND A.STAFF_ID=MED LIMIT 1);
SELECT 1 INTO #EOK FROM STAFF_CONVENIOS A WHERE A.CONV_ID=CONVE AND A.STAFF_ID=MED LIMIT 1;
SET BTEMP=IF(#EOK IS NULL,TRUE,FALSE);
SET OK= OK AND BTEMP ;
END IF;
IF (OK) THEN
SET VHORA=VHORAI;
IF (VDURACAO IS NULL) THEN
SET VDURACAO=30;
END IF;
WHILE (VHORA <= VHORAF) DO
SET BOCUP=(SELECT 1 FROM AGENDA_STAFF A WHERE A.DATA_MARCADA=DATAREF AND A.HORA_MARCADA=VHORA);
IF (BOCUP IS NULL) THEN
INSERT INTO TBLRESULTS VALUES (DATAREF,VDIA,VHORA,VMED_ID,VNOMEMED,VESPEC_ID,VNOMEESPEC);
END IF;
SET VHORA=ADDTIME(VHORA, VDURACAO * 100);
END WHILE;
SET VHORA=ADDTIME(VHORA, VDURACAO * (-100));
IF (VHORA < VHORAF) THEN
SET VHORA=VHORAF;
SET BOCUP=(SELECT 1 FROM AGENDA_STAFF A WHERE A.DATA_MARCADA=DATAREF AND A.HORA_MARCADA=VHORA);
IF (BOCUP IS NULL) THEN
INSERT INTO TBLRESULTS VALUES (DATAREF,VDIA,VHORA,VMED_ID,VNOMEMED,VESPEC_ID,VNOMEESPEC);
END IF;
END IF;
END IF;
UNTIL BDONE END REPEAT;
CLOSE CURS;
SELECT A.* FROM TBLRESULTS A LEFT JOIN AGENDA_STAFF B ON B.STAFF_ID=A.MED_ID AND B.HORA_MARCADA=A.HORA AND B.DATA_MARCADA=A.DATA_AG;
END
//
The problem is with the lines:
-- SET #EOK=(SELECT 1 FROM STAFF_CONVENIOS A WHERE A.CONV_ID=CONVE AND A.STAFF_ID=MED LIMIT 1);
SELECT 1 INTO #EOK FROM STAFF_CONVENIOS A WHERE A.CONV_ID=CONVE AND A.STAFF_ID=MED LIMIT 1;
If I use "SET #EOK..." all works well.
If I use SELECT 1 INTO #EOK.. the problem appears.
More info with data
Expected result from call p_gethorarios(7,'2017-11-20',47,21)
"data_ag";"dia";"hora";"med_id";"nome_med";"espec_id";"nome_espec"
"2017-11-20";"2";"08:30:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
"2017-11-20";"2";"09:00:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
"2017-11-20";"2";"09:30:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
"2017-11-20";"2";"10:00:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
"2017-11-20";"2";"08:30:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
"2017-11-20";"2";"09:00:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
"2017-11-20";"2";"09:30:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
"2017-11-20";"2";"10:00:00";"7";"Paulo Renato Scofano";"47";"Pediatria/Neonatologia"
STAFF-ESCALA TABLE
ID;STAFF_ID;DIA;HINI;HFIM;ESPEC_ID;DURACAO;CREATION_TIME;MODIFICATION_TIME;LAST_USER_MODIF
25;7;2;08:00:00;10:00:00;50;;18/11/2017 21:44:02;;1
26;7;6;08:00:00;10:00:00;50;;18/11/2017 21:55:27;;1
27;7;4;08:00:00;10:00:00;50;;18/11/2017 21:55:27;;1
28;7;5;08:00:00;10:00:00;50;;18/11/2017 21:56:36;;1
35;7;3;08:00:00;10:00:00;47;;19/11/2017 19:10:29;;1
36;7;5;08:00:00;10:00:00;47;;19/11/2017 19:10:29;;1
38;7;2;08:00:00;10:00:00;47;;19/11/2017 19:10:29;;1
You may have to use user/session variables (the #xyz kind). The documentation does not explicitly state such, but it only shows examples with them.
https://dev.mysql.com/doc/refman/5.7/en/select-into.html
If it is an issue with the NOT FOUND handler getting triggered from something other than the cursor, you could try structuring your code something like this (very pseudocode):
FETCH
WHILE( NOT DONE )
BEGIN
DO STUFF
SET DONE = FALSE
FETCH
END

Updation not done in procedure after inserting a record in same table

I inserted record into a table with the help of Cursor and loop after closing cursor i wrote update statement to update some record which inserted by cursor so reords not updating. but i ran query outside then records updating
my try is
drop procedure if exists kpsf_inopdormantac;
create procedure kpsf_inopdormantac(inp_branchcode varchar(6), inp_date date)
begin declare c_branchcode varchar(6);
declare c_accounttype varchar(4);
declare c_accountsubtype varchar(6);
declare c_accountno varchar(12);
declare c_lasttxndate date;
declare c_inopdate date;
declare c_temp varchar(25);
declare c1 cursor for SELECT
branchcode, accounttype, accountsubtype, accountno, lasttxndate, inoperativedate FROM accountmaster WHERE branchcode = inp_branchcode AND accounttype in ('10','11') AND accountstatus!='C' AND lasttxndate < ( SELECT date_add(inp_date,interval -24 month));
truncate table inopdormantac;
commit;
open c1;
loop1:loop fetch c1 into c_branchcode, c_accounttype, c_accountsubtype, c_accountno, c_lasttxndate, c_inopdate;
INSERT into inopdormantac (branchcode, accounttype, accountsubtype, accountno, acstatus, lasttxndate, inopdate)
VALUES
(c_branchcode, c_accounttype, c_accountsubtype, c_accountno, 'InOperative', c_lasttxndate, c_inopdate);
end loop loop1;
close c1;
set c_temp='InActive';
update inopdormantac SET acstatus = c_temp WHERE lasttxndate < ( SELECT
date_add('2015-10-06',interval -120 month));
end;
plz help me
Potentially you might be running DB instance in safe-updates mode. Please see another question which have been already answered:
MySQL error code: 1175 during UPDATE in MySQL Workbench

Cursor to copy distinct record from one table to another

I want to copy all recoreds from temp1 table to anoter two tables I am using cursor for this .
DELIMITER //
CREATE PROCEDURE cpyQ()
BEGIN
DECLARE g_id INT DEFAULT 0;
DECLARE v_fn varchar(100);
DECLARE v_ln varchar(100);
DECLARE v_email varchar(100);
declare tcursor for select distinct mailid,fname,lname from temp1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET flag = 1;
OPEN tcursor;
REPEAT
FETCH cursor into v_fn,v_ln, v_email;
insert into atom(type) values('Person');
SET g_id = LAST_INSERT_ID();
insert into user(id,fname,lname,mailid) values(g_id,v_fname,v_lname,v_email);
END REPEAT;
CLOSE tcursor;
END//
DELIMITER
this code is showing error
MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'for select distinct mailid,fname,lname from temp1;
DECLARE CONTINUE HANDLE' at line 8
How to resolve this
You have multiple errors in your syntax and don't exit the loop. Try this?
CREATE PROCEDURE cpyQ()
BEGIN
DECLARE g_id INT DEFAULT 0;
DECLARE v_fn varchar(100);
DECLARE v_ln varchar(100);
DECLARE v_email varchar(100);
DECLARE done INT DEFAULT FALSE;
declare tcursor cursor for select distinct mailid,fname,lname from temp1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN tcursor;
read_loop: LOOP
FETCH tcursor into v_fn,v_ln, v_email;
if done then
LEAVE read_loop;
END IF;
insert into atom(type) values('Person');
SET g_id = LAST_INSERT_ID();
insert into user(id,fname,lname,mailid) values(g_id,v_fn,v_ln,v_email);
END LOOP;
CLOSE tcursor;
END
I tried this query and find this is working
insert into atom(id,type) select id,'Person' from user1;
INSERT INTO user( id, fname, lname, mailid ) SELECT id, fname, lname, mailid FROM user1;

Trigger is not working properly

I have create trigger for some condition but its through error.
Here is trigger code.
DELIMITER //
CREATE TRIGGER `getcrm`.`update_round_date` AFTER UPDATE ON `getcrm`.`vtiger_stockcheckcf`
FOR EACH ROW begin
DECLARE retribAn INTEGER DEFAULT 0;
DECLARE curEdate datetime;
DECLARE done INT DEFAULT 0;
DECLARE curTipo CURSOR FOR
SELECT a.*, b.*, c.* FROM vtiger_crmentity AS a, vtiger_stockcheck AS b,vtiger_stockcheckcf AS c WHERE a.crmid = b.stockcheckid AND a.crmid = c.stockcheckid AND c.cf_746 = 'Pending' AND a.setype='StockCheck';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
OPEN curTipo;
REPEAT
FETCH curTipo INTO retribAn;
IF NOT done THEN
set curEdate = NOW();
IF a.createdtime = curEdate AND c.cf_746 = Pending THEN
INSERT INTO vtiger_cancellationcf(scheckid,cf_1150,cf_1152,cf_1154,cf_1156,cf_1151,cf_1153,cf_1155,cf_1157,cf_1158,cf_1160,cf_1162,cf_1159,
cf_1161,cf_1163,cf_1203,cf_1178,cf_1180,cf_1182,cf_1184,cf_1186,cf_1178,cf_1180,cf_1182,cf_1184,cf_1186,cf_1179,cf_1181,
cf_1183,cf_1185,cf_1187,cf_1179,cf_1181,cf_1183,cf_1185,cf_1187,cf_1164,cf_1166,cf_1168,cf_1170,cf_1165,cf_1167,cf_1169,
cf_1171,cf_1173,cf_1176,cf_1177,cf_1172,cf_1174,cf_1175,cf_1188,cf_1189,cf_1190) values ('a.crmid','"c.cf_709"','"c.cf_711"','"c.cf_713"','"c.cf_715"','"c.cf_710"','"c.cf_712"','"c.cf_714"',
'"c.cf_716"','"c.cf_717"','"c.cf_719"','"c.cf_721"','"c.cf_718"','"c.cf_720"','"c.cf_844"','"c.cf_1079"','"c.cf_736"',
'"c.cf_738"','"c.cf_740"','"c.cf_742"','"c.cf_744"','"c.cf_737"','"c.cf_739"','"c.cf_741"','"c.cf_743"','"c.cf_745"',
'"c.cf_722"','"c.cf_724"','"c.cf_726"','"c.cf_723"','"c.cf_725"','"c.cf_727"','"c.cf_729"','"c.cf_731"','"c.cf_734"',
'"c.cf_735"','"c.cf_730"','"c.cf_732"','"c.cf_733"','"b.stockcheck"','"c.cf_746"','"c.cf_1080"','"c.cf_1081"');
insert into vtiger_cancellation (cancellationid,cancellation,scheckid) values ('a.crmid',' ','c.cf_709');
insert into vtiger_crmentity (crmid,smcreatorid,smownerid,modifiedby,setype,description,createdtime,modifiedtime,viewedtime,status,version,presence,deleted,label) values ('a.crmid','a.smcreatorid','a.smownerid','a.smcreatorid','Cancellation','','curEdate','curEdate','','','0','1','0','');
delete FROM vtiger_crmentity_seq where id='a.crmid';
insert into vtiger_crmentity_seq (id)values ('a.crmid');
END IF;
END IF;
UNTIL done END REPEAT;
CLOSE curTipo;
end
//
DELIMITER
Here is error when any changes on table.
1328 - Incorrect number of FETCH variables
Thanks for advance
I think the problem is here : FETCH curTipo INTO retribAn; your trying to fetch a complete row into a integer.
You should read more on CURSORS .
EXAMPLE:
DECLARE a CHAR(16);
DECLARE b INT;
DECLARE cur1 CURSOR FOR SELECT id,data FROM test.t1;
OPEN cur1;
FETCH cur1 INTO a, b;

MySQL Stored Procedure Nested Cursors Error

i am copying data for a Many to Many Relationship table making a Third Table.
The stored procedure currently looks like this but it has some error
DELIMITER $$
CREATE PROCEDURE `test`.UpdateRelatedAccounts()
BEGIN
DECLARE ssn_sel_id VARCHAR(255) DEFAULT 0;
DECLARE id_sel_id CHAR(36) DEFAULT 0;
DECLARE id_sel_rel CHAR(36) DEFAULT 0;
DECLARE no_more_rows BOOLEAN;
DECLARE num_rows INT DEFAULT 0;
DECLARE no_more_rel_rows BOOLEAN;
DECLARE rel_num_rows INT DEFAULT 0;
DECLARE ssn_all_cur CURSOR FOR
SELECT ssn, id FROM ssn WHERE ssn NOT IN ('','000-00-0000');
DECLARE ssn_cur CURSOR FOR
SELECT id FROM ssn WHERE id != id_sel_id AND ssn = ssn_sel_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = TRUE;
-- DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rel_rows = TRUE;
OPEN ssn_all_cur;
SELECT FOUND_ROWS() INTO num_rows;
the_loop: LOOP
FETCH ssn_all_cur
INTO ssn_sel_id, id_sel_id;
IF no_more_rows THEN
CLOSE ssn_all_cur;
LEAVE the_loop;
END IF;
OPEN ssn_cur;
SELECT FOUND_ROWS() INTO rel_num_rows;
the_rel_loop: LOOP
FETCH ssn_cur
INTO id_sel_rel;
IF no_more_rel_rows THEN
CLOSE ssn_cur;
LEAVE the_rel_loop;
END IF;
INSERT INTO `ssn_related` ( `ssn_primary`, `ssn_related` ) VALUES ( id_sel_id, id_sel_rel ), ( id_sel_rel, id_sel_id );
END LOOP the_rel_loop;
END LOOP the_loop;
END$$
DELIMITER ;
How do i nest to use the values and insert into third table.
Cursors are slow and most of the time unnecessary. Nested cursors are slow² and unnecessary². Cursors shall only be used as the last resort, when there's really no other way.
What you want to do can be broken down to this:
INSERT INTO `ssn_related` ( `ssn_primary`, `ssn_related` )
SELECT
ssn_1.id,
ssn_2.id
FROM
ssn ssn_1
INNER JOIN ssn ssn_2 ON ssn_2.ssn = ssn_1.id
WHERE ssn_1.ssn NOT IN ('', '000-00-0000')
AND ssn_2.id != ssn_1.id;
Then you do the same again with swapped columns in the SELECT.
INSERT INTO `ssn_related` ( `ssn_primary`, `ssn_related` )
SELECT
ssn_2.id,
ssn_1.id
FROM
ssn ssn_1
INNER JOIN ssn ssn_2 ON ssn_2.ssn = ssn_1.id
WHERE ssn_1.ssn NOT IN ('', '000-00-0000')
AND ssn_2.id != ssn_1.id;