Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - Adding a string to a text column (concat equivalent)

How do you add a string to a column in SQL Server?

UPDATE [myTable] SET [myText]=' '+[myText] 

That doesn't work:

The data types varchar and text are incompatible in the add operator.

You would use concat on MySQL, but how do you do it on SQL Server?

like image 295
Aximili Avatar asked Jun 23 '10 05:06

Aximili


People also ask

How do I concatenate a string in a column in SQL?

To append a string to another and return one result, use the || operator. This adds two strings from the left and right together and returns one result. If you use the name of the column, don't enclose it in quotes. However, in using a string value as a space or text, enclose it in quotes.

What can I use instead of concat in SQL?

We can use nvarchar(max) or varchar(max) instead. SQL string functions are used to manipulate the character expressions or to obtain various information about them. CONCAT function in SQL is one of the most useful members of these functions.

Can we use concat and substring together in SQL?

First, use CONCAT to get the customers' full name. Then use CONCAT and SUBSTR together to retrieve the email, use REPEAT and INSTR to censor it and use AS to rename the column. With INSTR we will identify a string ( email ) and specify a certain character ( @ )as the starting position we want in the string.


2 Answers

like said before best would be to set datatype of the column to nvarchar(max), but if that's not possible you can do the following using cast or convert:

-- create a test table  create table test (     a text )  -- insert test value insert into test (a) values ('this is a text') -- the following does not work !!! update test set a = a + ' and a new text added' -- but this way it works:  update test set a = cast ( a as nvarchar(max))  + cast (' and a new text added' as nvarchar(max) ) -- test result select * from test -- column a contains: this is a text and a new text added 

hope that helps

like image 63
Tobias Pirzer Avatar answered Sep 28 '22 08:09

Tobias Pirzer


Stop using the TEXT data type in SQL Server!

It's been deprecated since the 2005 version. Use VARCHAR(MAX) instead, if you need more than 8000 characters.

The TEXT data type doesn't support the normal string functions, while VARCHAR(MAX) does - your statement would work just fine, if you'd be using just VARCHAR types.

like image 22
marc_s Avatar answered Sep 28 '22 08:09

marc_s