k.troy2012
k.troy2012

Reputation: 344

TSQL: Insert Into Table with if condition

I've made a small simple table here:

declare @live bit = 1
declare @temp table(id int, title varchar(30))

insert into @temp (id, title)
select 1, 'myTitle1'
union select 2, 'myTitle2'
union select 3, 'myTitle3'

select * from @temp

Output:

id  title
-------------
1   myTitle1
2   myTitle2
3   myTitle3

Now I want the title attribute to be dependent from @live

I'll show it in pseudo-code:

declare @live bit = 1
declare @temp table(id int, title varchar(30))

insert into @temp (id, title)
select 1, IF (@live == 1) THEN 'myTitle1_live' ELSE 'myTitle1'
union select 2, IF (@live == 1) THEN 'myTitle2_live' ELSE 'myTitle2'
union select 3, IF (@live == 1) THEN 'myTitle3_live' ELSE 'myTitle3'

select * from @temp

How would this look in sql syntax?

Upvotes: 0

Views: 34

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269853

I think you just want a conditional expression:

select id,
       (case when @live = 1 then concat(title, '_live') else title end)
from @temp;

If the data is already in the table, then you would use update:

update t
    set @title = concat(title, '_live')
    from @temp t
    where @live = 1;

Upvotes: 1

Related Questions