SQL Server Insert if not exists

Cover Image for SQL Server Insert if not exists
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

How to Insert Data into SQL Server Table Only if it Doesn't Exist 🗄️

Are you tired of duplicating data in your SQL Server table? Do you want to ensure that only unique data gets inserted? 🤔 Well, you're in luck! In this blog post, we'll explore a common issue faced by SQL developers: how to insert data into a table only if it doesn't already exist.

The Problem 👾

Let's say we have a EmailsRecebidos table that stores received emails. We want to insert new email information into this table, but only if it doesn't already exist. If a duplicate email is inserted, it should be ignored to prevent data redundancy.

The Frustrating Code 😩

Here is the code that we have initially tried:

ALTER PROCEDURE [dbo].[EmailsRecebidosInsert]
  (@_DE nvarchar(50),
   @_ASSUNTO nvarchar(50),
   @_DATA nvarchar(30) )
AS
BEGIN
   INSERT INTO EmailsRecebidos (De, Assunto, Data)
   VALUES (@_DE, @_ASSUNTO, @_DATA)
   WHERE NOT EXISTS ( SELECT * FROM EmailsRecebidos 
                   WHERE De = @_DE
                   AND Assunto = @_ASSUNTO
                   AND Data = @_DATA);
END

The Confusing Error 🚫

But running this code triggers the following error message:

Msg 156, Level 15, State 1, Procedure EmailsRecebidosInsert, Line 11 Incorrect syntax near the keyword 'WHERE'.

The Solution 💡

The reason for the error is that the WHERE clause cannot be used directly with the INSERT INTO statement. To overcome this limitation, we can use the MERGE statement to achieve the desired functionality.

Here's an updated version of the code using the MERGE statement:

ALTER PROCEDURE [dbo].[EmailsRecebidosInsert]
  (@_DE nvarchar(50),
   @_ASSUNTO nvarchar(50),
   @_DATA nvarchar(30) )
AS
BEGIN
   MERGE EmailsRecebidos AS target
   USING (SELECT @_DE AS De, @_ASSUNTO AS Assunto, @_DATA AS Data) AS source
   ON (target.De = source.De
       AND target.Assunto = source.Assunto
       AND target.Data = source.Data)
   WHEN NOT MATCHED THEN
       INSERT (De, Assunto, Data)
       VALUES (source.De, source.Assunto, source.Data);
END

Now, when executing the stored procedure, this code will insert a new row into the table only if the combination of De, Assunto, and Data values doesn't already exist in the EmailsRecebidos table.

The Call-to-Action 📣

You're now armed with the knowledge to insert data into a SQL Server table only if it doesn't exist. Give it a try and let us know how it worked for you! If you have any questions or encountered any issues, feel free to leave a comment below. Happy coding! 💻🚀


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello