0

I have a question how can I convert a SQL Server column with data of type nvarchar to float?

Classic query:

ALTER TABLE <column>
ALTER COLUMN <column> FLOAT;

works only with an empty column.

Is there any way to do this?

Thanks!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
michal
  • 11
  • 3

2 Answers2

1

Normal classic query works even with columns having data, not only empty ones. But the issue arises when the Nvarchar column holds incompatible data. So best option is to create a new table or create new column and use Try_Convert.. (only from SQL Server 2012)

This works:

create table #t
(
    id nvarchar(3)
)

insert into #t
    select 1
    union all
    select 2

alter table #t
alter column id float--this works

This fails:

create table #t
(
   id nvarchar(3)
)

insert into #t
select 1
union all
select 2

insert into #t
select 'a'

alter table #t
alter column id float--this fails

So best way is to use try_convert and take decision on null values which is incompatible data

create table #t1
(
    id float
)

insert into #t1
    select try_convert(float, id) 
    from #t

Update:

If you are on SQL Server 2008 R2 or below, you can use this technique instead of TRY_Convert. Taken from Mikael excellent answer

declare @T table
(
  Col varchar(50)
)

insert into @T values
('1'),
('1.1'),
('1,1'),
('1a')

select cast('' as xml).value('sql:column("Col") cast as xs:decimal ?', 
                             'decimal(28,10)') as Col
from @T

Output:

Col
-------------
1.0000000000
1.1000000000
NULL
NULL
Community
  • 1
  • 1
TheGameiswar
  • 27,855
  • 8
  • 56
  • 94
0

You should use the following syntax:

ALTER TABLE table_name
ALTER COLUMN column_name datatype