简体   繁体   中英

Insert a row if it doesn't exist via query

I am trying to write a query that will insert a group of people into a table if that person does not exist. For example, I have table full of people and I need to add more people into the database and I don't know if they are already there. I do know that the social security number (ssn) will never be the same for two people. Could a query be used to check if the ssn is in the table and if not insert the person into the table? If the ssn is in the table then go to the next person and check?

I was thinking about using a stored procedure, but I do not have any rights to create a store procedure.

You can insert your data into a table variable or temp table and then INSERT INTO table from temp table where it does not exists in your table.

DECLARE @Inserted AS TABLE
    (
     NAME VARCHAR(50)
    ,SSN DECIMAL(10, 0)
    )


INSERT INTO @Inserted
        ( NAME, SSN )
    VALUES  ( 'Bob', 123456789 )
    ,       ( 'John', 123546789 )
    ,       ( 'James', 123456798 )

INSERT INTO MyTable
        SELECT *
            FROM @Inserted AS i
            LEFT OUTER JOIN MyTable AS m
                ON i.SSN = m.SSN
            WHERE m.SSN IS NULL

Here are a couple ideas to get you started. I use MERGE a lot because it offers so much control. You could also look into the IN clause as part of a WHERE predicate in the INSERT SELECT statement.

MERGE

DECLARE @PERSONTABLE TABLE (ID INT PRIMARY KEY IDENTITY(1,1), FirstName VARCHAR(max))
INSERT INTO @PERSONTABLE (FirstName) VALUES ('Bill'),('Sally'),('Bob')

DECLARE @NEWPEOPLE TABLE (FirstName VARCHAR(max))
INSERT INTO @NEWPEOPLE (FirstName) VALUES ('Jim'), ('Sally')

--MERGE
MERGE INTO @PERSONTABLE AS T
USING @NEWPEOPLE AS S
ON (T.FirstName = S.FirstName)
WHEN NOT MATCHED BY TARGET THEN
    INSERT (FirstName) VALUES (S.FirstName);

SELECT * FROM @PERSONTABLE

EXCEPT

DECLARE @PERSONTABLE TABLE (ID INT PRIMARY KEY IDENTITY(1,1), FirstName VARCHAR(max))
    INSERT INTO @PERSONTABLE (FirstName) VALUES ('Bill'),('Sally'),('Bob')

    DECLARE @NEWPEOPLE TABLE (FirstName VARCHAR(max))
    INSERT INTO @NEWPEOPLE (FirstName) VALUES ('Jim'), ('Sally')

    --EXCEPT

    INSERT INTO @PERSONTABLE (FirstName)
    SELECT FirstName FROM @NEWPEOPLE
    EXCEPT
    SELECT FirstName FROM @PERSONTABLE

    SELECT * FROM @PERSONTABLE

You could do it like this if the new people are in another table. If not, then use Vladimir's solution.

INSERT INTO People(ssn, firstname, lastname)
SELECT ssn, firstname, lastname
FROM   newpeople 
WHERE  ssn not in (select ssn from people )
INSERT INTO People(ssn, firstname, lastname)
SELECT np.ssn, np.firstname, np.lastname
FROM newpeople np
LEFT JOIN People p on np.ssn = p.ssn
WHERE p.ssn IS NULL

Here's another option I use a lot. Normally joins are better than sub-selects... if the joined table value is null you know you don't have a hit in the joined table.

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