views:

43

answers:

4

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  A: 

Try this:

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

or

SELECT Cast( foold AS SQL_CHAR(10) ) + ' ' + fooName FROM mytable
Alex W
A: 

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

Whats the error you getting?

ozczecho
+4  A: 

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)
OMG Ponies
SQL Server 2008. I've edited the original post.
Gabe
Ah, this one is much more complete than my answer. +1
Justin K
A: 

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

Justin K