Using if-else Statement while Inserting the Record in SQL Server Database

Today we will learn that how to use an if-else statement while inserting records into the database. We are talking about the SQL Server database. To understand this example we are understanding a problem that will make easy to  learn if-else statement. Our problem is we want to insert a record into the table named “StudentRecord”. This table have two columns named ‘student_name’ and ‘student_gender’. We will pass the name and gender as parameter in the stored procedure. Now we have to edit the name according to his/her gender. for example if the student_gender = ‘Male’ then we will add ‘Mr.’ before the name of student. Similarly if the student_gender = ‘Female’ then we will add ‘Mrs/Miss’ before the name of student. Now we are showing that how this task will be done.



Create/alter procedure sp_InsertStudentRecord

@student_name varchar(50),

@student_gender varchar(6)

as

begin

declare @fullname varchar(60)

if @student_gender=’Male’

begin

set @fullname=”Mr.” + @student_name

end

else

begin

set @fullname=”Miss/Mrs.” + @student_name

end

insert into StudentRecord(Student_name,Student_gender)

values(@fullname,@student_gender)

end

admin (157 Posts)


Comment ( 1 )

  1. SUNIL KUMARFebruary 24, 2013 18 // Reply

    Nice Tutorial

Leave a reply

Your email address will not be published.

Comment moderation is enabled. Your comment may take some time to appear.