Friday, March 9, 2012

How to use if then statement in a sql stored procedure?


How do you use an if then statement in a sql stored procedure? I have a table with 3 columns in it. When the table
is updated, I will only need one particular column in the database updated at a time. I will signal which column to update with
an integer value(WhichColumn). So I want to key off that value to determine which column is to be updated.

Here is my pseudo code

if(WhichColumn EQUALS 1)
{
Update InsertEntry SET FirstColumn=Value
}
else if(WhichColumn EQUALS 2)
{
Update InsertEntry SET SecondColumn=Value
}
else if(WhichColumn EQUALS 3)
{
Update InsertEntry SET ThirdColumn=Value
}


Here is a rough start to my stored procedure to incorporate the logic above
GO
CREATE PROCEDURE [dbo].[InsertEntry]
(
WhichColumn int
Value nvarchar(500),

)


CREATE PROCEDURE [dbo].[InsertEntry]
(
@.WhichColumn int,
@.Value nvarchar(500)

)

AS

if(WhichColumn = 1)
{
Update InsertEntry SETFirstColumn=@.Value
}
else if(WhichColumn = 2)
{
Update InsertEntry SETSecondColumn=@.Value
}
else if(WhichColumn = 3)
{
Update InsertEntry SETThirdColumn=@.Value
}

|||

You cant use { } in SQL server 2000 or SQL.

the if - clause in SQL is like this:

if(condition)

begin

do xyz..

end

else

begin

do abc...

end

Your solution is like this:

set @.col= ()

if(@.col=1)

begin

do xyz

end

else

begin

if(col=2)

begin

end

else

begin

if(col=3)

begin

end

end

end

No comments:

Post a Comment