Click here to Skip to main content
15,886,787 members
Articles / Database Development / SQL Server / SQL Server 2014
Tip/Trick

Microsoft SQL: Increase Existing Value In Row Or Add New Row If None Exists

Rate me:
Please Sign up or sign in to vote.
2.92/5 (8 votes)
20 Mar 2015CPOL1 min read 11.1K   5   3
Yes, Virginia, You Can Do This All With One Simple SQL Statement

Introduction

This is not a blockbuster SQL tip, but since I didn't find anything like this already online, I wanted to pass this along so that others can quickly port my solution to their project.

Background

Let's imagine that you are analyzing different sources for news articles and you're counting how many times a particular source publishes an article containing a particular keyword. Consequently, your database has a table with the following three columns:

  1. SourceID (int)
  2. Keyword (string)
  3. KeywordCount (int)

For example, in a particular row, the SourceID might equal "12345". The keyword might equal "gold" and the keyword count might equal 100.

Now, let's imagine that you analyze another 10 articles from this source and the word "gold" appears in 6 of those articles. You want to increase the KeywordCount value by 6.

However, it's also possible that you could have a totally new keyword for this source (for example, "silver") and instead of adding 6 to an existing row, you want to create a new row for this keyword (and add the count value).

Here's an easy way to do it with one line of Microsoft SQL.

Using the Code

Let's imagine that you have the following values:

SQL
tempSourceID = int
tempKeyword = String
tempKeywordCount = int

You would use the following SQL call:

SQL
Dim upsertCommand As SqlCommand = connection.CreateCommand

upsertCommand.CommandText = "IF EXISTS (SELECT 1 FROM (Table_Name) _
WHERE SourceID = @TempSourceID) UPDATE (Table_Name) SET KeywordCount = _
(KeywordCount + @TempKeywordCount) WHERE SourceID=@TempSourceID AND _
Keyword = @TempKeyword ELSE INSERT INTO (Table_Name) _
(SourceID, Keyword, KeywordCount) VALUES (@TempSourceID, @TempKeyword, @TempKeywordCount)"

upsertCommand.Parameters.AddWithValue("@TempKeywordCount", tempKeywordCount)
upsertCommand.Parameters.AddWithValue("@TempSourceID", tempSourceID)
upsertCommand.Parameters.AddWithValue("@TempKeyword", tempKeyword)

Try
    upsertCommand.ExecuteNonQuery()
Catch ex As Exception
    (Handle error here)
Finally
     connection.Close()
End Try

Points of Interest

I saw a number of other attempts at doing this which seemed to require a lot more commands to accomplish what I've done above. Any feedback is appreciated!

History

  • 20th March, 2015: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionUse the MERGE command Pin
szalkovics20-Mar-15 12:37
szalkovics20-Mar-15 12:37 
AnswerRe: Use the MERGE command Pin
furytrader20-Mar-15 14:57
furytrader20-Mar-15 14:57 
GeneralDon't use MERGE, don't use IF EXISTS ... Pin
Christophe Van Olmen23-Mar-15 22:26
professionalChristophe Van Olmen23-Mar-15 22:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.