Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL INSERT INTO SELECT, combine varchar columns

Tags:

sql

sql-server

Say I have a table with columns firstName and lastName. Is it possible to do an INSERT INTO newTable SELECT firstName, lastName FROM oldTable, but instead of having two columns in the resulting table, concatenate the two columns?

Similarly, is it possible to concatenate a column with a static string?

like image 271
carpat Avatar asked May 14 '26 04:05

carpat


1 Answers

Yes, you'd do

SELECT LTRIM(RTRIM(ISNULL(firstName, '') + ' ' + ISNULL(lastName, ''))) FROM oldTable

this concatinates the firstName and lastName columns, as well as the static string ' ' in between

EDIT: added LTRIM(RTRIM(...)) so if firstName or lastName is null, result won't have leading or trailing space as a result from the static ' ' string.

like image 90
Will P. Avatar answered May 15 '26 18:05

Will P.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!