문제

I need add a computed column to an SQL Server datatable to perfomrs a cast over another column in same table. Is there the best approach to achieve it or someone has a better idea?

Important note: StringValue column has a 5% or less of non numeric values, they must be parsed as zero.

ALTER TABLE dbo.Tabla ADD
    ParsedValue AS case isnumeric(StringValue) when 1 then cast(StringValue as decimal(18,4)) else 0 end PERSISTED 
GO

Thanks in advance,

도움이 되었습니까?

해결책

On SQL Server 2012 you can use TRY_CONVERT.

This is more reliable than isnumeric for this purpose.

ALTER TABLE dbo.Tabla
  ADD ParsedValue AS ISNULL(TRY_CONVERT(decimal(18, 4), StringValue), 0) PERSISTED 

I would consider not making it PERSISTED and not wrapping it in ISNULL for non numeric values though.

Treating non numeric values as 0 rather than NULL will mean that, for example, AVG calculations are not correct.

It is not necessary to mark it as PERSISTED to create an index on this column.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top