Published on: 22 Jan, 2014

How to use if condition in SQL Server?

Tumblr Digg Google Plus

You might come with a scenario where you need to use if condition when there are two possible cases occur. For example, when you develop a program or website, you want to do some sort of scheduling that can synchronize your current records with the existing data. In this tutorial, we will show you how you can simply create a stored procedure that will accept some sample data and will check if they are already exist then perform an update otherwise it will just insert a new record.

Let's say we have the following example table with those columns:

  • ID
  • Name
  • Value

The sample stored procedure we create will check if the Name is already exists. Note on this stage, we don't pass the ID as we just want to show you how it works.

CREATE PROCEDURE SyncData
	@Name nvarchar(100),
        @Value nvarchar(200)
AS
         /*** We declare a variable ID ***/
         DECLARE @ID INT 

         /*** We search the ID based on the given name ***/
         Select @ID = ID FROM tblData
         Where Name = @Name

         IF @ID > 0
              /*** If the ID is found we perform an update ***/
              BEGIN
                    UPDATE tblData
                    SET Value = @Value
                    WHERE ID = @ID
              END 
         ELSE
              /*** ID is not found then we insert the data. We assume the ID is Identity Field (automatically insert in this case) ***/
              BEGIN
                   INSERT INTO tblData(
                        Name ,
                        Value 
                   )VALUES(
                        @Name ,
                        @Value 
                   )
              END 

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.