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

Filed in SQLTags: , , , ,

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

Sourabh Sharma (150 Posts)


Feedback

Comments

One Response to “Using if-else Statement while Inserting the Record in SQL Server Database”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>