Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

sql - 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...