W
W
winniuss2019-12-16 14:03:40
SQL Server
winniuss, 2019-12-16 14:03:40

How to add to a database table without repeats?

I have a table. I fill it with students. Then I delete some rows from the table. How can I add only those lines that have been removed? If you fill in the primary key again, then there will be an error that such ones already exist. And if you turn it off, then there will be duplicates.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2019-12-17
@winniuss

insert into Students
select list.Id, list.[Name] 
from 
(values	
  (1,N'Вася'),
  (2,N'Петя'),
  (3,N'Женя'),
  (4,N'Коля'),
  (5,N'Настя'),
  (6,N'Аристарх'),
  (7,N'Никодим')
) list (Id, [Name])
left join Students s on s.Id = list.Id
where s.Id IS NULL

S
Stanislav Shendakov, 2019-12-17
@shindax

Maybe INSERT ON DUPLICATE KEY UPDATE will do?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question