DB

[MSSQL] INSERT NOT EXISTS

오선지♬ 2023. 2. 7. 19:18
728x90
반응형

 

https://mitch.codes/sql-tip-insert-where-not-exists/

 

SQL Tip - Insert where not exists - Mitch Valenta

Recently I had an issue where I needed to do a unique insert to a SQL database from a webapp.

mitch.codes

 

SELECT 문의 결과값이 없을 경우에 INSERT 하는 방법.

 

INSERT INTO dbo.table (field) 
SELECT 'field'
WHERE NOT EXISTS 
    (SELECT field 
     FROM dbo.table
     WHERE field = 'field')
 
INSERT INTO dbo.Customer (firstname, lastname, phone) 
SELECT 'Mitch', 'Valenta', '555-867-5309'
WHERE NOT EXISTS 
    (SELECT firstname, lastname 
     FROM dbo.Customer 
     WHERE firstname = 'Mitch' AND lastname = 'Valenta')
728x90
반응형

'DB' 카테고리의 다른 글

[DB][MySQL] timestamp 자동  (0) 2023.02.23
[Mybatis] insert return 값  (0) 2023.02.11
[MSSQL] NUMERIC DECIMAL 차이 ?  (0) 2023.01.21
[Mybatis] statementType CALLABLE  (0) 2023.01.17
[SQL][Mybatis] <collection>  (0) 2023.01.13