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

hfwmuf9z  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(278)

我在这里做了一张简单的小table:

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

现在我希望title属性依赖于@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语法中是什么样子的?

lrpiutwd

lrpiutwd1#

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

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;

相关问题