Home > Software engineering >  Inserting value based on any condition in SQL
Inserting value based on any condition in SQL

Time:04-26

declare @varID as INT = 2

insert into table1
(
ID
,varName
)
select
ID
,**#####**
from table2

I want value of varName based on @varID. How can I do that?

What should be in place of #####?

Statement that replicate IF @varname = 2 then 'P' else 'I'.

CodePudding user response:

You are very close. Just mention the variable in the SELECT clause. Like this.

declare @varID as INT = 2

insert into table1 (ID ,varName)
select  ID, 
        CASE WHEN @varID = 2 THEN 'P' ELSE 'I' END
from table2

CodePudding user response:

Maybe a CASE WHEN THEN ELSE END statement like below

declare @varID as INT = 2

insert into table1
(
ID
,varName
)
select
ID
,CASE WHEN @varID=2 THEN 'P' ELSE 'I' END
from table2
  • Related