IMG-LOGO

How to use if condition in SQL Server?

andy - 22 Jan, 2014 2841 Views 0 Comment

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.

Related Articles

How to restore database using SQL query in TSQL?

If you have a database backup bak file extension and want to restore it using SQL query You can use the built in RESTORE DATABASE function Remember in order to be able to restore a database successfully You need to ...

How to get all table sizes in TSQL?

To get the information about how much space or size used by tables You can retrieve the size information by linking multiple tables in sys tables There are two tables that hold this information The first one is the sys ...