Use Create view to convert a varchar field and contents to number field - type-conversion

I have table with a Varchar field. See structure.
IMAGE_KEY VARCHAR2(32 BYTE)
DOC_TYPE VARCHAR2(8 BYTE)
DOC_KEY VARCHAR2(256 BYTE)
LAST_UPDT DATE
UPDT_USER VARCHAR2(6 BYTE)
BLK_HANDLE VARCHAR2(16 BYTE)
DOC_KEY_ID NUMBER(15,0)
FE_ID NUMBER(15,0)
I want to create a view and convert the field Doc_Type which is varchar to a Number field in the view using the sql scripts.
SELECT IMAGE_KEY,
DOC_TYPE,
cast(DOC_KEY as NUMBER(15)) as DOC_KEY ,
LAST_UPDT,
UPDT_USER,
BLK_HANDLE,
DOC_KEY_ID,
FE_ID
FROM rdo
and
SELECT IMAGE_KEY,
DOC_TYPE,
TO_NUMBER (TRIM (DOC_KEY)) as DOC_KEY ,
LAST_UPDT,
UPDT_USER,
BLK_HANDLE,
DOC_KEY_ID,
FE_ID
FROM rdo
I get the following error when I extract data from the views created by any of the scripts above.
An error was encountered performing the requested operation:
ORA-01722: invalid number
01722. 00000 - "invalid number"
*Cause: The specified number was invalid.
*Action: Specify a valid number.
Vendor code 1722
How do I successfully convert the varchar field to a Number field using a create view statement.

Related

How to find average of the column

Thanks in advance.
How to find avg when the column datatype is character varying in PostgreSQL.
here growth and literacy are character-varying.
Select avg(cast(GROWTH as float)) from census2;
I have created a table name called census2
create table census2
(
District VARCHAR(200)
, STATE VARCHAR(250)
, Growth NUMERIC
, Sex_Ratio NUMERIC
, Literacy NUMERIC
);
After successful creation while adding CSV file it is displaying errors as
ERROR: invalid input syntax for type numeric: "Growth"
CONTEXT: COPY census2, line 503, column growth: "Growth"

Check if character varying is between range of numbers

I hava data in my database and i need to select all data where 1 column number is between 1-100.
Im having problems, because i cant use - between 1 and 100; Because that column is character varying, not integer. But all data are numbers (i cant change it to integer).
Code;
dst_db1.eachRow("Select length_to_fault from diags where length_to_fault between 1 AND 100")
Error - operator does not exist: character varying >= integer
Since your column supposed to contain numeric values but is defined as text (or version of text) there will be times when it does not i.e. You need 2 validations: that the column actually contains numeric data and that it falls into your value restriction. So add the following predicates to your query.
and length_to_fault ~ '^\+?\d+(\.\d*)?$'
and length_to_fault::numeric <# ('[1.0,100.0]')::numrange;
The first builds a regexp that insures the column is a valid floating point value. The second insures the numeric value fall within the specified numeric range. See fiddle.
I understand you cannot change the database, but this looks like a good place for a check constraint esp. if n/a is the only non-numeric are allowed. You may want to talk with your DBA ans see about the following constraint.
alter table diags
add constraint length_to_fault_check
check ( lower(length_to_fault) = 'n/a'
or ( length_to_fault ~ '^\+?\d+(\.\d*)?$'
and length_to_fault::numeric <# ('[1.0,100.0]')::numrange
)
);
Then your query need only check that:
lower(lenth_to_fault) != 'n/a'
The below PostgreSQL query will work
SELECT length_to_fault FROM diags WHERE regexp_replace(length_to_fault, '[\s+]', '', 'g')::numeric BETWEEN 1 AND 100;

How to insert value into uuid column in Postgres?

I have a table with a uuid column, and some of the rows are missing the data. I need to insert data into this uuid column. The data is entered manually, so we are suffixing with other column data to differentiate, but it gives me an error.
UPDATE schema.table
SET uuid_column = CONCAT ('f7949f56-8840-5afa-8c6d-3b0f6e7f93e9', '-', id_column)
WHERE id_column = '1234';
Error: [42804] ERROR: column "uuid_column" is of type uuid but expression is of type text
Hint: You will need to rewrite or cast the expression.
Position: 45
I also tried
UPDATE schema.table
SET uuid_column = CONCAT ('f7949f56-8840-5afa-8c6d-3b0f6e7f93e9', '-', id_column)::uuid
WHERE id_column = '1234';
Error: [22P02] ERROR: invalid input syntax for uuid: "f7949f56-8840-5afa-8c6d-3b0f6e7f93e9-1234"
An UUID consists of 16 bytes, which you see displayed in hexadecimal notation.
You cannot have a UUID with fewer or more bytes.
I recommend using the type bytea if you really need to do such a thing.

Conversion failure varchar to int on a column cast as int

I've created a view called vReceivedEmail which includes a varchar column called RowPrimaryKeyValue. This column usually stores primary key id values, such as 567781, but every now and then has the descriptive text 'Ad hoc message'.
I've set the view up so that it only shows records that would hold the primary key values and then CAST the column as int.
SELECT CAST(Email.RowPrimaryKeyValue as int) as DetailID
FROM MessageStore.dbo.Email Email
WHERE ISNUMERIC(Email.RowPrimaryKeyValue) = 1
When I test the view, I only get records with the primary key values I expected, and when I look at the column listing for the view in the object explorer, the column is saved at the int data type.
I've then tried to apply the following WHERE clause in a separate query, referencing my saved view:
SELECT PotAcc.DetailID
FROM PotentialAccounts PotAcc
WHERE PotAcc.DetailID NOT IN (
SELECT RecEmail.DetailID
FROM vReceivedEmail RecEmail
)
...but I'm returning the following error:
Conversion failed when converting the varchar value 'Ad hoc message'
to data type int.
'Ad hoc message' is data from the column I filtered and converted to int, but I don't know how it's managing to trip up on this since the view explcitly filters this out and converts the column to int.
Since you are on SQL Server 2012, how about using try_convert(int,RowPrimaryKeyValue) is not null instead of isnumeric()?
Your view would look like so:
select try_convert(int, RowPrimaryKeyValue) as DetailID
from MessageStore.dbo.Email Email
where try_convert(int, RowPrimaryKeyValue) is not null
In SQL Server 2012 and up: each of these will return null when the conversion fails instead of an error.
try_convert(datatype,val)
try_cast(val as datatype)
try_parse(val as datatype [using culture])
Why doesn’t isnumeric() work correctly? (SQL Spackle)
Isnumeric() can be deceiving... however I'm betting this is due to SQL Server optimization. Though your view works, that doesn't mean the outer query guarantees that only INT is returned. Instead of using a view... use a CTE and try it. And since you are on 2012, this can all be avoided how SqlZim explained above.
WITH CTE AS(
SELECT CAST(Email.RowPrimaryKeyValue as int) as DetailID
FROM MessageStore.dbo.Email Email
WHERE ISNUMERIC(Email.RowPrimaryKeyValue) = 1)
SELECT PotAcc.DetailID
FROM PotentialAccounts PotAcc
WHERE PotAcc.DetailID NOT IN (
SELECT RecEmail.DetailID
FROM CTE RecEmail
)

BYTEA to Integer using libpq

I have a table with two columns:
1) id SERIAL PRIMARY KEY 2) BYTEA
I am trying to fetch all the rows using PGresult * res = PQexecParams(conn, "select * from table",0,NULL,NULL,NULL,NULL,1); ==> The last argument = 1 specify results to be in binary format.
Due to the last argument, I am able to fetch BYTEA column properly but the "id" column is also returned in a format that I can't understand(probably in BYTEA format). Is there a way to convert the "id" value returned by the above mentioned PQexecParams to integer? I am using PQgetvalue API to fetch results.