SQL 将 varchar 列与 int 列组合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3150943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 06:43:26  来源:igfitidea点击:

Combine varchar column with int column

sqlsql-serversql-server-2008

提问by Gabe

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

我在 SQL 表中有两列,fooId(int) 和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.

此字段将直接在 Web 应用程序的控件中进行数据绑定。

SQL Server 2008

SQL Server 2008

(I'm a bit of a sql beginner)

(我是一个 sql 初学者)

回答by OMG Ponies

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
  1. 连接方法/运算符
  2. 如果数据库处理隐式数据类型转换

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

SQL Server不会将数字隐式转换为字符串值:

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.

...因此您需要使用CAST(或 CONVERT)将数据类型显式更改为基于文本的数据类型。

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

对于Oracle 和 PostgreSQL,使用双管道连接字符串:

SELECT fooid || ' ' || fooname

For MySQL, you can use the CONCAT function:

对于MySQL,您可以使用CONCAT 函数

SELECT CONCAT(fooid, ' ', fooname)

回答by Alex W

Try this:

尝试这个:

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

or

或者

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

回答by ozczecho

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

是的,应该没问题,只要绑定字段是字符串。

Whats the error you getting?

你得到什么错误?

回答by Justin K

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

我不确定它是否是标准 SQL,但 PostgreSQL 使用该||运算符进行字符串连接。+表示数字加法。

回答by Sourcephy

I use this query in MS SQL

我在 MS SQL 中使用这个查询

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

Assuming varcharColumn is null

假设 varcharColumn 为空

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