Rick
Rick

Reputation: 2308

SQL Server: Computed Column with different datatypes

I am trying to get a field to display the combination of a a field with data type int and another as nvarchar under Computed Column Specification, but am getting the following error:

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

Computed Column Specification Forumula: [myNvarCharField] + ' ' + [myIntField]

Is it not possible to concatenate fields from different datatypes under the Computed Column Specification in SQL Server 2008?

Upvotes: 0

Views: 3496

Answers (2)

gbn
gbn

Reputation: 432271

When you mix datatypes in an expression, implicit conversions happen according to "datatype precedence". Int is higher precedence than nvarchar so CAST the int first

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

Upvotes: 1

user596075
user596075

Reputation:

Here is how you would use a string and an int as computed column math. Try this:

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

Upvotes: 2

Related Questions