简体   繁体   中英

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

I have #Temp2 which has columns:

Math_Text, Science_Text, Physics_Text, Title

I need to run the query below:

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

When I run it, for example, I see CombinedText = 'Math_Text' but I need the actual value under that column. What can I do? Thanks!

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 

did not work as well, t2.Title stays instead turning into its actual value.

EDIT2:

set CombinedText = c.[t2.Title+''_Text''] also did not work

This is a very poor data design. You should have your "text" columns in separate rows rather than columns.

With that in mind, you could do:

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
         );

You could also use a giant case expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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