TSQL:使用if条件插入到表中



我在这里制作了一个简单的小表:

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

输出:

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

现在我希望标题属性依赖于@live

我将以伪代码显示:

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

这在sql语法中会是什么样子?

我想你只需要一个条件表达式:

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

如果数据已经在表中,那么您将使用update:

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

最新更新