Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way using T-SQL / MS-SQL to append a string to existing table cells?

I have a table with a 'filename' column. I recently performed an insert into this column but in my haste forgot to append the file extension to all the filenames entered. Fortunately they are all '.jpg' images.

How can I easily update the 'filename' column of these inserted fields (assuming I can select the recent rows based on known id values) to include the '.jpg' extension?

like image 946
Matt Mitchell Avatar asked Aug 20 '08 08:08

Matt Mitchell


People also ask

Which character is used to append strings in SQL?

The + operator allows you to add two or more strings together. Note: See also the CONCAT() and CONCAT_WS() functions.

How do I concatenate a string to a variable in SQL Server?

Concatenates two strings and sets the string to the result of the operation. For example, if a variable @x equals 'Adventure', then @x += 'Works' takes the original value of @x, adds 'Works' to the string, and sets @x to that new value 'AdventureWorks'.

How do you append data to an existing table in SQL?

On the Home tab, in the View group, click View, and then click Design View. On the Design tab, in the Query Type group, click Append. The Append dialog box appears. Next, you specify whether to append records to a table in the current database, or to a table in a different database.


3 Answers

MattMitchell's answer is correct if the column is a CHAR(20), but is not true if it was a VARCHAR(20) and the spaces hadn't been explicitly entered.

If you do try it on a CHAR field without the RTRIM function you will get a "String or binary data would be truncated" error.

like image 187
samjudson Avatar answered Oct 14 '22 16:10

samjudson


The solution is:

UPDATE tablename SET [filename] = RTRIM([filename]) + '.jpg' WHERE id > 50

RTRIM is required because otherwise the [filename] column in its entirety will be selected for the string concatenation i.e. if it is a varchar(20) column and filename is only 10 letters long then it will still select those 10 letters and then 10 spaces. This will in turn result in an error as you try to fit 20 + 3 characters into a 20 character long field.

like image 27
Matt Mitchell Avatar answered Oct 14 '22 16:10

Matt Mitchell


Nice easy one I think.

update MyTable
set filename = filename + '.jpg'
where ...

Edit: Ooh +1 to @MattMitchell's answer for the rtrim suggestion.

like image 4
Matt Hamilton Avatar answered Oct 14 '22 16:10

Matt Hamilton