Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update table column with data from other columns in same row

Tags:

sql-server

I have a table that has several columns of textual data. The goal is to concatenate those columns into a single different column in the same table and same row.

What is the SQL Server query syntax that would allow me to do this?

like image 685
Jason Miesionczek Avatar asked Dec 04 '22 20:12

Jason Miesionczek


2 Answers

Something like this:

UPDATE myTable SET X = Y + Z
like image 116
Paddy Avatar answered Feb 24 '23 14:02

Paddy


Do you absolutely have to duplicate your data? If one of the column values changes, you will have to update the concatenated value.

A computed column:

alter table dbo.MyTable add ConcatenatedColumn = ColumnA + ColumnB

Or a view:

create view dbo.MyView as
select ColumnA, ColumnB, ColumnA + ColumnB as 'ConcatenatedColumn'
from dbo.MyTable

Now you can update ColumnA or ColumnB, and ConcatenatedColumn will always be in sync. If that's the behaviour you need, of course.

like image 36
Pondlife Avatar answered Feb 24 '23 14:02

Pondlife