SQL Server:具有不同数据类型的计算列

时间:2011-10-06 02:14:51

标签: sql-server-2008

我试图让一个字段显示一个字段与数据类型为int的组合,另一个字段显示为计算列规范下的nvarchar,但是我收到以下错误:

Conversion failed when converting the nvarchar value 'y' to data type int.

计算列规范论坛:[myNvarCharField] +''+ [myIntField]

是否无法在SQL Server 2008中的计算列规范下连接不同数据类型的字段?

2 个答案:

答案 0 :(得分:2)

以下是如何使用字符串和int作为计算列数学。试试这个:

create table TestComputedCols
(
    someint int not null,
    somestring nvarchar(10) not null,
    combination as (somestring + ' ' + cast(someint as nvarchar))
)

答案 1 :(得分:1)

当您在表达式中混合数据类型时,隐式转换根据“datatype precedence"发生.Int优先于nvarchar,因此CAST首先是int

...
MyComputedColumn AS [myNvarCharField] + ' ' + CAST([myIntField] AS nvarchar)
...