【问题标题】:TSQL: Insert Into Table with if conditionTSQL:使用 if 条件插入表
【发布时间】:2020-11-23 13:49:31
【问题描述】:

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

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 语法中看起来如何?

【问题讨论】:

  • 您可能正在寻找CASE

标签: sql tsql select insert union


【解决方案1】:

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

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2012-08-29
    相关资源
    最近更新 更多