Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate text in a query in sql server?

Tags:

sql

sql-server

The following SQL:

SELECT notes + 'SomeText' FROM NotesTable a  

Give the error:

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

like image 636
oglester Avatar asked Sep 10 '08 15:09

oglester


People also ask

How do you concatenate the results of SQL query?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

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.

Can you concatenate in SQL?

In SQL, you can also concatenate numerical data from the table in the same way as we concatenate strings. The CONCAT function can also be used to join numeric values.


2 Answers

The only way would be to convert your text field into an nvarchar field.

Select Cast(notes as nvarchar(4000)) + 'SomeText' From NotesTable a 

Otherwise, I suggest doing the concatenation in your application.

like image 66
GateKiller Avatar answered Oct 12 '22 12:10

GateKiller


You might want to consider NULL values as well. In your example, if the column notes has a null value, then the resulting value will be NULL. If you want the null values to behave as empty strings (so that the answer comes out 'SomeText'), then use the IsNull function:

Select IsNull(Cast(notes as nvarchar(4000)),'') + 'SomeText' From NotesTable a 
like image 42
Chris Wuestefeld Avatar answered Oct 12 '22 12:10

Chris Wuestefeld