I have a table with a column A.
I would like to change the datatype from string to float.
My column A looks like this:
A
143
1,440
19,630
12
...
When I try to run my code:
ALTER TABLE [Table1]
ALTER COLUMN [A] FLOAT
I always get this error:
Error converting data type varchar to float.
It is clear in error that varchar value is not converting into float. Since , is not allowed in int, float, decimal type values, so first need to replace your , .
Instead of this you may try this.
update table set A = Replace( A, ',', '' )
Or
update table set A = Replace( A, ',', '.' )
Whichever condition suits you better.
After that convert your column.
ALTER TABLE [Table1]
ALTER COLUMN [A] FLOAT
Related
Why does this keep happening? The first 2 data types are Int. The 'Games' is DateTime. The last is VarChar. Why is it not executing successfully
CREATE TABLE JaretSchedule
(
FieldID int Primary,
TeamID int Foreign,
Games DateTime,
TeamsPlaying varChar
);
INSERT INTO [dbo].[JaretsSchedule]
([FieldID]
,[TeamID]
,[Games]
,[TeamsPlaying])
VALUES('1', '1', '2012-01-20 12:00:00', 'Roadrunners v.s. Cheetahs');
Error Message: String or binary data would be truncated. The statement has been terminated
Because ,you have exceeded the max size of field,
ALTER TABLE JaretsSchedule ALTER COLUMN TeamsPlaying nvarchar(1000);
The default length of varchar when used as a column data type is 1.
varchar [ ( n | max ) ] Variable-size string data
. . .
When n isn't specified in a data definition or variable declaration
statement, the default length is 1. If n isn't specified when using
the CAST and CONVERT functions, the default length is 30.
char and varchar (Transact-SQL)
So you need so set a max length for the column. EG
use tempdb
go
drop table if exists JaretsSchedule
go
create table JaretsSchedule
(
FieldId int,
TeamID int,
Games datetime,
TeamsPlaying varchar(255)
)
go
insert into JaretsSchedule(FieldId,TeamID,Games,TeamsPlaying)
values (1,1,'2012-01-20 10:00:00','Roadrunnersv.s.Cheetahs')
I have a column of type DECIMAL(8,0).
I'm trying to update a blank/space/empty sting(' ') based on condition.
update table1
set col1 = cast('' as decimal(8,0))
where value = '5'
I'm getting this error:
Error converting data type varchar to numeric.
How to update blank/space/empty sting(' ') in the column of decimal datatype?
You can't convert whitespace to a decimal data type.
I have a table ConsoleGames wherein all columns are of type varchar(50). When I try to create a new table console_games by amending existing datatypes by using the query:
CREATE TABLE console_games
(
game_rank integer,
game_name varchar(1200),
platform_name varchar(1200),
game_year integer,
genre varchar(200),
publisher varchar(1200),
na_sales float,
eu_sales float,
jp_sales float,
other_sales float
)
INSERT INTO console_games
SELECT *
FROM [dbo].[RAWConsoleGames]
I get the following error message:
Msg 245, Level 16, State 1, Line 17
Conversion failed when converting the varchar value 'SAT' to data type int.
When I look into the data in the table the value 'SAT' is in a column for which I am not changing the datatype. 'SAT' value exists in the Platform column which is of varchar type and I am not trying to change the type to int.
Any help will be appreciated.
Thanks
Clearly 'SAT' is not and will never convert to an INT.
Always best to specify the columns to insert ... things change
Now, if the source data is suspect, add a try_convert(). If the conversion fails, a null value will be returned
I don't know the column names of your source, so I substituted SomeColN
INSERT INTO console_games
SELECT try_convert(integer ,SomeCol1)
,try_convert(varchar(1200),SomeCol2)
,try_convert(varchar(1200),SomeCol3)
,try_convert(integer ,SomeCol4)
,try_convert(varchar(200) ,SomeCol5)
,try_convert(varchar(1200),SomeCol6)
,try_convert(float ,SomeCol7)
,try_convert(float ,SomeCol8)
,try_convert(float ,SomeCol9)
,try_convert(float ,SomeCol10)
FROM [dbo].[RAWConsoleGames]
Just for fun, try:
Select try_convert(int,'SAT')
Select try_convert(int,'25.25')
Select try_convert(int,'25')
You should always define the list of columns you're inserting into, and you should also always define the list of columns you're selecting from. Furthermore, I'd recommend to explicitly do any type conversions instead of leaving that up to SQL Server - if you do it yourself, you know when and what you're doing.
So I'd write that statement like this:
-- **DEFINE** the list of columns you're inserting into
INSERT INTO console_games (rank, name, Platform, year, genre, publisher,
sales, eu_sales, jp_sales, other_sales)
-- **DEFINE** the list of columns you're selecting, and any conversions
SELECT
game_rank, game_name, platform_name,
CAST(game_year AS VARCHAR(50)), genre,
publisher,
CAST(na_sales AS VARCHAR(50)),
CAST(eu_sales AS VARCHAR(50)),
CAST(jp_sales AS VARCHAR(50)),
CAST(other_sales AS VARCHAR(50))
FROM
[dbo].[RAWConsoleGames]
Hi i want to alter my table from nvarchar to float when my table contain values
i'm trying this code:
alter table MY_TABLE alter column PRICE float
But i get error Msg 8114, Level 16, State 5, Line 1 Error converting
data type nvarchar to float.
You have a problem, because some value cannot be converted to a float.
So, get rid of that value first:
update my_table
set price = try_convert(float, price);
Then the conversion will work:
alter table MY_TABLE alter column PRICE float;
I should note: float is a bad data type for a "price" column. It should really be a numeric or money type.
In SQL Server 2008, use isnumeric() instead:
update my_table
set price = NULL
where isnumeric(price) = 0
First Update the bad records
Update MY_TABLE set PRICE = Replace(Replace(Price,',','.'),' ','')
Then run the alter
alter table MY_TABLE alter column PRICE float;
To Insert into new table
Insert into table_name (Price,col1,..)
Select Replace(Replace(Price,',','.'),' ',''),col1,col2,..
From MY_TABLE
FLOAT is a approximate datatype will not store exact value
Review Data that can't be converted
Select * from MY_TABLE where IsNumeric(PRICE)=0
If this data can be destroyed or has no value otherwise edit where necessary
Update MY_TABLE Set PRICE = null where IsNumeric(PRICE)=0
Alter table MY_TABLE alter column PRICE float
I am trying to create view by filtering some table, and include some converted to different type column into select list. View filter excludes from result set rows in which this column can not be converted to that type. Then I select rows from this view and filter rows using this converted column. And I always get error Conversion failed when converting the nvarchar value '2aaa' to data type int
SQL Fiddle
MS SQL Server 2008 Schema Setup:
create table _tmp_aaa (id int identity(1, 1), value nvarchar(max) not null)
go
insert _tmp_aaa (value) values ('1111'), ('11'), ('2aaa')
go
create view _tmp_v_aaa
as
select id, cast(value as int) as value from _tmp_aaa where value like '1%'
go
Query 1:
select * from _tmp_v_aaa where value = 11
Are there any workarounds?
Add to your view ISNUMERIC to check if string is numeric value:
CREATE VIEW _tmp_v_aaa
AS
SELECT
id,
[value] = CAST((CASE WHEN ISNUMERIC([value]) = 1 THEN [value] ELSE NULL END) AS INT)
FROM _tmp_aaa
WHERE [value] LIKE '1%'
AND ISNUMERIC([value]) = 1
I tried some tricks... Obviously the optimizer tries to hand down your where criterium where it is not yet tranformed. This is one problem to be solved with a. multi-statement function. Their biggest disadvantage is the advantage in this case: the optimizer will not look into it, but just take their result "as is":
create function fn_tmp_v_aaa()
returns #tbl table(id INT, value INT)
as
BEGIN
INSERT INTO #tbl
select id, cast(value as int) as value from _tmp_aaa where value like '1%'
RETURN;
END
select * from dbo.fn_tmp_v_aaa() where value=11;
If you look at the execution plan , predicates are passed down to the table something like....
And your query gets translated to something like .....
select id, cast(value as int) as value
from tmp_aaa
where CONVERT(INT, value,0) like '1%'
AND CONVERT(INT, value,0) = CONVERT(INT, 11,0)
Now if you run this query you will get the same error you get when you query against the view.
Conversion failed when converting the nvarchar value '2aaa' to data type int.
When the predicate CONVERT(INT, value,0) like '1%' is converted , you have INT on one side of the expressions and varchar on another, INT being the higher precedence, sql server tries to convert whole expression to INT and fails hence the error message.