質問

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