Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine varchar column with int column

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)

like image 386
Gabe Avatar asked Jun 30 '10 15:06

Gabe


People also ask

How do you concatenate int and varchar columns in SQL?

In the earlier version of SQL Server, we usually use CONVERT function to convert int into varchar and then concatenate it. Given below is the script. Solution 2: In this solution, we will use CONCAT function (a newly shipped function in SQL Server 2012) to convert int into varchar then concatenate it.

Can a varchar be cast to an int?

SQL Server's CAST() and CONVERT() methods can be used to convert VARCHAR to INT.

How do I concatenate two columns with different data types in SQL?

Solution. TSQL provides 2 ways to concatenate data, the + sign and the new CONCAT() function. This tip will cover the differences in the two, so you can achieve the expected behavior in your code. The way most us are used to concatenating data together is using the + sign.

How do I combine two column values in SQL?

SELECT SOME_OTHER_COLUMN, CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME FROM `customer`; Using * means, in your results you want all the columns of the table. In your case * will also include FIRSTNAME . You are then concatenating some columns and using alias of FIRSTNAME .


2 Answers

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) 
like image 86
OMG Ponies Avatar answered Oct 11 '22 11:10

OMG Ponies


Try this:

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

or

SELECT Cast( foold AS SQL_CHAR(10) ) + ' ' + fooName FROM mytable 
like image 33
Alex W Avatar answered Oct 11 '22 13:10

Alex W