Why can't I modify column type in Postgres - sql

I am trying to change type of columns from varchar to integer. When I run the following command
alter table audio_session
alter column module_type_cd type INT USING module_type_cd::integer,
alter column sound_type_cd type INT USING sound_type_cd::integer
I got the error:
ERROR: invalid input syntax for integer: "string"
SQL state: 22P02
The error does not make any sense. There is no "string" in the command at all. What did I do wrong?

The columns audio_session.module_type_cd or audio_session.sound_type_cd has at least one non-numeric value among all values of each row. So, it's impossible to convert to a completely numeric data type.
As an example :
create table Table1( col1 varchar(10), col2 varchar(10) );
insert into Table1 values('1','1');
insert into Table1 values('2','2');
insert into Table1 values('3','C3');
select CAST(coalesce(col1, '0') AS integer) as converted from Table1; -- this works
select CAST(coalesce(col2, '0') AS integer) as converted from Table1; -- but, this doesn't
SQL Fiddle Demo

There is no "string" in the command at all.
But must be in the data. The command you're going to use tries to cast all the columns values to integer. Check this:
select *
from audio_session
where module_type_cd = 'string' or sound_type_cd = 'string';

Related

Convert ntext to numeric

One of my column is defined as ntext datatype which is no longer supported by many streams. I'm trying my best to convert that column to numeric or int and every attempt is reaching anywhere.
reg_no #my ntext field | name | country | etc |
I tried to alter the col using the command we all use, but failed
alter table tabl1
alter column [reg_no] numeric(38,0)
Error:
Error converting data type nvarchar to numeric
Any suggestions on fixing this or has anyone come across this in the past, if yes how did you get over it
You should be able to do this in two steps:
alter table tabl1 alter column [reg_no] nvarchar(max);
alter table tabl1 alter column [reg_no] numeric(38,0);
ntext is deprecated and conversion to numeric is not supported, but converting to nvarchar() is supported.
This assumes that the values are compatible with numeric. Otherwise you will get a type conversion error. If this happens, you can get the offending values by using:
select *
from t
where try_convert(numeric(38, 0), try_convert(nvarchar(max), x)) is null
Try,
select convert(int,convcert(varchar(40), reg_no)) as newfieldname from tabl1

varchar to numeric:Error converting data type varchar to numeric

I am trying to convert a column formatted in varchar to decimal(19,12) with the following line of code
ALTER TABLE [tablename]
ALTER COLUMN [columnname][format]
and get the following prompt:
Msg 8114, Level 16, State 5, Line 25
Error converting data type varchar to numeric.
Has worked before like a charm. The issue here seems to be that the values in the column are 19 or so digit numeric values formatted as text.
I tried to create a new column, pasted shortened cell values (used the left() function) into it from the original column but that doesn't seem to do the trick either since the code above ends up occationally with the additional "Arithmetic overflow occurred." message.
When some of the rows have incorrect values, ALTER COLUMN would not work. A typical course of action goes like this:
Add a new column of the desired type
Update the column with values that you would like to keep
Drop the old column
Rename the new column
Step 2 would go like this:
UPDATE MyTable
SET NewColumn =
CASE WHEN ISNUMERIC(OldColumn)=1 AND DATALENGTH(OldColumn) <= 19 THEN
CAST(OldColumn AS decimal(19,12))
ELSE
NULL
END
You could also turn ANSI warnings off with SET ANSI_WARNINGS OFF command, which would let you run ALTER COLUMN ignoring data trunction errors. The drawback of this approach is that potential errors get ignored. On the other hand, when you do conversion explicitly with a CASE expression you have an option to supply an alternative value for the error case (I used NULL above, but you can put any number you want).
Could you try to seperate your problem? This does work on SQL 2012:
set nocount on
if object_id ('tempdb..#t1') is not null drop table #t1
create table #t1 (c1 varchar(100))
insert #t1 values ('1234567.8901234567890')
select * from #t1
alter table #t1
alter column c1 decimal(19,12)
select * from #t1
If you play around a bit with the strings you easily can produce an arimetic overflow error. But 'Error converting data type varchar to numeric' needs character or empty sting.
Maybe you can try with your data?

SQL - How to change data type float to nvarchar and remove scientific notation

How do I change the data type float to nvarchar in order to remove the scientific notation and still keep precision? Consider the following:
CREATE TABLE ConversionDataType (ColumnData FLOAT);
INSERT INTO ConversionDataType VALUES (25566685456126);
INSERT INTO ConversionDataType VALUES (12345545546845);
INSERT INTO ConversionDataType VALUES (12345545545257);
When I do a simple read I get the following data, as expected:
select * from ConversionDataType
ColumnData
------------------------------------
25566685456126
12345545546845
12345545545257
Now when I try update the data type to an nvarchar, it gets stored in scientific notation which is something I don't want:
update ConversionDataType
set ColumnData = CAST(ColumnData AS NVARCHAR)
The result set is as follows:
25566700000000
12345500000000
12345500000000
It replaces some digits and adds zeros after the 6th index. How can I go about this? I had a look at the Convert function but that is only for converting date time data types.
Being valid what others said in comment, if you just want to convert float to varchar without scientific notation, you need to convert to numeric. You can try this:
SELECT CAST(CAST(CAST(25566685456126291 AS FLOAT) AS NUMERIC) AS NVARCHAR)
Output:
C1
------------------------------
25566685456126292
Whereas
SELECT CAST(CAST(25566685456126291 AS FLOAT) AS NVARCHAR) AS C1
gives:
C1
------------------------------
2.55667e+016
If you need to change datatype, I think you should add a new column, update it and (if you want) delete the old column and rename the new column at the end.
CREATE TABLE TEST1 (C1 FLOAT)
INSERT INTO TEST1 VALUES (25566685456126291);
ALTER TABLE TEST1 ADD C2 VARCHAR(18)
UPDATE TEST1 SET C2=CAST(CAST(C1 AS NUMERIC) AS VARCHAR)
SELECT * FROM TEST1
Output:
C1 C2
---------------------- ------------------
2.55666854561263E+16 25566685456126292
FLOAT was a very bad decision as this is not a precise data type. If you wanted to store the phone numbers as numbers, you'd have to go for DECIMAL instead.
But you'll have to use NVARCHAR instead. And this is the only reasonable design, as phone numbers can have leading zeros or start with a plus sign. So the first thing is to introduce an NVARCHAR column:
ALTER TABLE ConversionDataType ADD ColumnDataNew NVARCHAR(30);
The function to convert a number into a string in SQL Server is FORMAT. It lets you state the format you want to use for the conversion, which is integer in your case (a simple '0'):
update ConversionDataType set ColumnDataNew = format(ColumnData, '0');
At last remove the old column and then rename the new one with the same name. SQL Server lacks an ALTER TABLE syntax to rename a column, so we must call sp_RENAME instead (at least this is what I have read on the Internet; here is a link to the docs: https://msdn.microsoft.com/de-de/library/ms188351.aspx).
ALTER TABLE ConversionDataType DROP COLUMN ColumnData;
EXEC sp_RENAME 'ConversionDataType.ColumnDataNew', 'ColumnData', 'COLUMN';
Here you can see the results: http://rextester.com/GLLB27702
SELECT CONVERT(NVARCHAR(250), StudentID) FROM TableA
StudentID is your Float Column of database
or Simply use
SELECT CONVERT(NVARCHAR(250), yourFloatVariable)

sql server conversion failed

I am querying a database in which I am getting the following exception:
Conversion failed when converting varchar value 'B6UJ978023EC' to data type int
How can I fix it?
My guess is that your query looks something like this:
select * from mytable where SomeField = 'B6UJ978023EC'
If that's the case, SomeField was declared as an INT datatype and Sql Server is attempting to convert 'B6UJ978023EC' to an INT which won't work.
It's possible that you're trying to do an insert/update, so this wouldn't work either if SomeField is an INT.
update mytable
set SomeField = 'B6UJ978023EC'
where something = something
insert mytable (field1, field2, SomeField)
values(123, 'abc', 'B6UJ978023EC')
Same result, Conversion failed when converting varchar value 'B6UJ978023EC' to data type int
In this case, either change the datatype of the column, or change the value of the variable.
Update:
If your column's datatype is (N)VARCHAR but contains some real numbers, then you can simply add single quotes around the number you're looking for.
-- works
select * from mytable where SomeField = '123456'
-- doesn't work - same error
select * from mytable where SomeField = 123456
try this:
Error is because you are trying to convert a character value to integer value. Just add the below condition to the query so that it will select only integer values
where ISNUMERIC(col+ '.0e0')=1

SQL union between NULL and VARCHAR error

I have two views with identical columns. One of the columns on the first view is generated 'on the fly' and set as NULL and the same column on the other view has values stored as varchar. I have a stored proc that looks like this:
ALTER PROCEDURE [dbo].[mi_GetLearners]
(#centrename nvarchar(200))
AS
SELECT [centrename]
,[Name]
,[Username] --generated on the fly as NULL
FROM [DB1].[dbo].[vw_Learners]
WHERE [centrename] = #centrename
UNION
SELECT [centrename]
,[Name]
,[Username] --values stored as varchar
FROM [Linked_Server].[DB2].[dbo].[vw_Learners]
WHERE [centrename] = #centrename
DB1 is on SQL Server 2008 R2
DB2 is on SQL server 2005
When I run the stored proc I get the following error:
Msg 245, Level 16, State 1, Line 1 Conversion failed when converting
the varchar value 'someusername' to data type int.
Why is it trying to convert the value to int datatype as the other column is set as NULL? If I instead change the second column from NULL to ' ' the stored proc works fine... I'm really baffled as to why a union between a varchar column and NULL column generated in a select statement would throw such an error... any ideas?
EDIT: I'm looking for an explanation rather than a solution...
EDIT 2: Running the following code:
CREATE VIEW vw_myview
AS
SELECT NULL AS MyColumn
EXECUTE sp_help vw_myview
Returns:
Type Column_name
int MyColumn
The problem is that NULL is (to within some wiggle room) a member of every data type.
When any SELECT query is being run, the contents of each column must be of one type, and only one type. When there are a mixture of values in a column (including NULLs), the type can obviously be determined by examining the types of the non-NULL values, and appropriate conversions are performed, as necessary.
But, when all rows contain NULL for a particular column, and the NULL hasn't been cast to a particular type, then there's no type information to use. So, SQL Server, somewhat arbitrarily, decides that the type of this column is int.
create view V1
as
select 'abc' as Col1,null as Col2
go
create view V2
as
select 'abc' as Col1,CAST(null as varchar(100)) as Col2
V1 has columns of type varchar(3) and int.
V2 has columns of type varchar(3) and varchar(100).
I'd expect the type of the field to be determined by the first SELECT in the union. You may try changing the order of your two selects or change to CAST(NULL AS VARCHAR(...)).
I think you need to cast to the same datatype:
---
AS
SELECT [centrename]
,[Name]
,CAST(NULL AS VARCHAR(MAX)) AS [Username]
FROM [DB1].[dbo].[vw_Learners]
WHERE [centrename] = #centrename
UNION
---