I am using VS2005 and SQL Server 2005.
I am trying to execute multiple INSERT INTO SQL statements which connect 3 sql tables.
The 3 tables are:
Table1:UserID, UsernameTable2:UserID, StatusTable3:UserID, Username, Issue
The following are the checks that I need to perform:
-
Users that exist in
Table1should exist inTable2 -
Users that exist in
Table1should not haveSTATUS=DELETEinTable2 -
Users that do not have
STATUS=DELETEinTable2should exist inTable1
Currently I only have a SELECT statement which fulfills the above 3 queries, without adding in the 3rd table:
SELECT *
FROM table1 t1
FULL OUTER JOIN table2 t2 ON t1.userid = t2.userid
WHERE (t2.userid IS NULL AND t1.userid IS NOT NULL)
OR (t2.status = 'DELETE' AND t1.userid IS NOT NULL)
OR (t2.userid IS NOT NULL AND t2.status <> 'DELETE' AND t1.userid IS NULL)
I would like to, for each check above, INSERT the results into Table3 with a unique ISSUE variable (e.g. for check no.1, ISSUE=User exist in t1 but not t2)
Currently I am trying to form a query which connects the 3 tables together, and for each result found by the first check, t2.userid IS NULL AND t1.userid IS NOT NULL, it will insert a new row into Table3. But I am having some problems with the SQL query.
INSERT INTO Table3 (userid, username, issue)
VALUES (t1.userid, t1.username, 'user not found in t2')
FULL OUTER JOIN table2 t2 ON t1.userid = t2.userid
WHERE (t2.userid IS NULL AND t1.userid IS NOT NULL)
Thank you very much for the help.
I do not have these tables for testing, so the syntax will be close:
The
COALESCEfor theUserIdwill ensure that you have a value inserted into the column, since you are not sure if the value will exist in Table1 or in Table2I also just used your where clauses for the
CASEstatements to fill theIssuecolumn. You can update the text to suit your application.