Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Concatenate integer and varchar

Author  Topic 

Apples
Posting Yak Master

146 Posts

Posted - 2008-02-29 : 11:49:22
I have a table like this:

tbl_Projects
-------------------------
ProjID | Description
-------------------------
1 | First
2 | Second
3 | Third

I want to write a SELECT statement that will output in this format:
1 - First
2 - Second
etc...

I've tried these two statements:

SELECT (ProjID + ' - ' + Description) AS Projects
FROM tbl_Projects
//Error: Conversion failed when converting the varchar value 'First' to data type int.

and

SELECT CONCAT(ProjID, CONCAT(' - ', Description)) AS Projects
FROM tbl_Projects
//Error: The data types int and varchar are incompatible in the concat operator.

Is there any way to concatenate an int value with a varchar value?

jdaman
Constraint Violating Yak Guru

354 Posts

Posted - 2008-02-29 : 11:58:51
[code]DECLARE @sample TABLE ( id INT, val VARCHAR(6) )
INSERT @sample ( id, val )
SELECT 1, 'First' UNION
SELECT 2, 'Second' UNION
SELECT 3, 'Third'

SELECT CAST(id AS VARCHAR)+' - '+val FROM @sample[/code]
Go to Top of Page

slimt_slimt
Aged Yak Warrior

746 Posts

Posted - 2008-03-01 : 16:10:50
you are having problems merging int and varchar field; i assume.

use CAST to convert int to varchar.


select
projid
,description
,cast(projId as varchar)+ ' - ' +description as full_name
from tbl_project
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2008-03-03 : 01:27:16
You should always specify length for character columns
http://sqlblogcasts.com/blogs/madhivanan/archive/2007/12/04/column-length-and-data-length.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -