开发者

Computed column should result to string

开发者 https://www.devze.com 2022-12-23 03:47 出处:网络
Here is a snap of my database. Both col1开发者_开发问答 and col2 are declared as int. My ComputedColumn currently adds the Columns 1 and 2, as follows...

Here is a snap of my database.

Both col1开发者_开发问答 and col2 are declared as int.

My ComputedColumn currently adds the Columns 1 and 2, as follows...

col1  col2  ComputedColumn
1     2     3
4     1     5

Instead of this, my ComputedColumn should join the columns 1 and 2 (includimg the '-' character in the middle) as follows...

col1  col2  ComputedColumn
1     2     1-2
4     1     4-1

So, what is the correct syntax?


You're probably defining your computed column as col1+col2. Try CAST(col1 AS NVARCHAR(MAX))+'-'+CAST(col2 AS NVARCHAR(MAX)) instead.

Or if you prefer, you can replace NVARCHAR(MAX) with NVARCHAR(10) or a different length of your choice.


create table TableName
(
    col1 int,
    col2 int,
    ComputedColumn as Convert(varchar, col1) + '-' + Convert(varchar, col2)
)

Bear in mind that if either value is null then the result of ComputedColumn will also be null (using the default collation and settings)


simple:

SELECT ComputedColumn = convert(varchar, col1) + '-' + convert(varchar, col2)
  FROM Table


SELECT col1, col2, (col1 + '-' + col2) as ComputedColumn

"+" is both addition and the concatenation character. You could explicitly convert, but in this case, including the '-' in the middle should cause an implicit conversion.


first create table in design mode

add 2 column as col1 and col2

add another column computedcolumn and set computed column property

Computed column should result to string

Also you can use that following script

CREATE TABLE [dbo].[tbl](
[col1] [varchar](50) NOT NULL,
[col2] [varchar](50) NOT NULL,
[ComputedColumn]  AS ((CONVERT([varchar],[col1],(0))+'-')+CONVERT([varchar],[col2],(0)))

)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号