繁体   English   中英

在SQL Server中更新时,在列而不是列名下获取值

[英]Get value under a column instead of columnname while updating in SQL Server

我有#Temp2有列:

Math_Text, Science_Text, Physics_Text, Title

我需要运行以下查询:

update t
set CombinedText = t2.Title + '_Text'
from #Temp1 t
inner #Temp2 t2 on t2.Id = t.Id

例如,当我运行它时,我看到CombinedText ='Math_Text'但我需要该列下的实际值。 我能做什么? 谢谢!

EDIT1:

declare @sql nvarchar(max) = 'update t
    set CombinedText = t2.Title + ''_Text''
    from #Temp1 t
    inner #Temp2 t2 on t2.Id = t.Id
'
exec sp_executesql @sql 

不起作用,t2.Title停留而不是变成它的实际价值。

EDIT2:

set CombinedText = c.[t2.Title+''_Text'']也不起作用

这是一个非常糟糕的数据设计。 您应该将“text”列放在单独的行而不是列中。

考虑到这一点,你可以这样做:

update t
    set CombinedText = v.txt
    from #Temp1 t inner join
         #Temp2 t2
         on t2.Id = t.Id cross apply
         (select v.*
          from (values ('Math', Math_Text), ('Science', Science_Text), ('Physics', Physics_Text)
               ) v(title, txt)
          where v.title = t2.title
         );

你也可以使用一个巨大的case表达。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM