27

I have two columns in a SQL table, fooId (int) and fooName (varchar).

Is there a way to select them both as one column with a space between them?

select fooId + ' ' + fooName as fooEntity
from mytable

They're different types so I'm getting an error.

This field will be databound directly in a control in the web app.

SQL Server 2008

(I'm a bit of a sql beginner)

1

5 Answers 5

39

String concatenation is different between databases, so it helps to know which database because you need to know:

  1. The concatenation method/operator
  2. If the database handles implicit data type conversion

SQL Server doesn't do implicit conversion of numeric into string values:

SELECT CAST(fooid AS VARCHAR(10)) + ' ' + fooname

...so you need to use CAST (or CONVERT) to explicitly change the data type to a text based data type.

For Oracle & PostgreSQL, use the double pipe to concatenate strings:

SELECT fooid || ' ' || fooname

For MySQL, you can use the CONCAT function:

SELECT CONCAT(fooid, ' ', fooname)
1
  • Ah, this one is much more complete than my answer. +1
    – Justin K
    Jun 30, 2010 at 15:54
2

Try this:

SELECT Convert( foold, SQL_CHAR ) + ' ' + fooName FROM mytable

or

SELECT Cast( foold AS SQL_CHAR(10) ) + ' ' + fooName FROM mytable
0

I'm not sure if it's standard SQL, but PostgreSQL uses the || operator for string concatenation. + means numerical addition.

0

I use this query in MS SQL

SELECT varcharColumn + CONVERT(VARCHAR(2), intColumn) AS foo

Assuming varcharColumn is null

SELECT ISNULL(varcharColumn, '') + CONVERT(VARCHAR(2), intColumn) AS foo
-1

Yeah that should be OK, as long as the bound field is a string.

Whats the error you getting?

1
  • 1
    This could have been a comment! Apr 17, 2018 at 19:38

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.