Unable to cast string to date when inserting on Databricks SQL - sql

I have a table created like so :
CREATE TABLE IF NOT EXISTS MyDataBase.Table (
`date` DATE,
`name` STRING,
`isTarget` BOOLEAN
) USING DELTA LOCATION '/mnt/path/to/folder/'
I need to manually insert values in the table using SQL. I tried to do it like so :
INSERT INTO CalendrierBancaire.Data VALUES (
('2022-01-01', 'New Year', True)
)
But it fails on this error :
Error in SQL statement: AnalysisException: cannot resolve 'CAST(`col1` AS DATE)' due to data type mismatch: cannot cast struct<col1:string,col2:string,col3:boolean> to date; line 1 pos 0;
I also tried to replace the date string with :
CAST('2022-01-01' AS DATE)
to_date('2022-01-01', 'yyyy-MM-dd')
But neither worked and returned the same error. It looks like the SQL parser wants to convert the whole row to date which is stupid. Do you have any idea how I can do it ?
Thanks.
PS : In real usage I have almost 30 to 40 lines to insert so letting a variable with the CAST expression while be painful to realize for all values.

It looks like the problem is that you have additional brackets around values that you want to insert, so it's interpreted as a single column - you need to use following syntax (see docs):
INSERT INTO CalendrierBancaire.Data VALUES
('2022-01-01', 'New Year', True)
or if you have multiple rows to insert, then list them via comma:
INSERT INTO CalendrierBancaire.Data VALUES
('2022-01-01', 'New Year', True),
('2022-02-01', 'New Year 2', True)
P.S. Although it works for me just fine even with extra brackets

Related

cx_Oracle.DatabaseError: ORA-00904: "DATETIME"."DATETIME": invalid identifier

I'm trying to export an Oracle DB with Python's cx_Oracle. I connect to DB, query all of the rows I need, and then build an INSERT statement with them.
I'm using code similar to this:
table_name = "AUDIT"
where_clause = "id > 10"
query = "SELECT * FROM " + table_name + " WHERE " + where_clause
curs = db_conn.cursor()
curs.execute(query)
res = curs.fetchall()
columns = []
for i in range(0, len(curs.description)):
columns.append(curs.description[i][0])
column_names = ",".join(columns)
statement = "INSERT INTO %s (%s) VALUES %s" % (table_name, column_names, row)
print statement
The types are NUMBER,VARCHAR2,DATE,NUMBER, and I get an insert statement that looks good... except for the date field:
INSERT INTO AUDIT_LOG (LOG_DBID,USER_NAME,EVENT_DATE,SEVERITY) VALUES ('AUDIT_LOG_SQ.nextval', 'user#do',datetime.datetime(2018, 4, 28, 1, 57, 42), '1')
When I try to execute this, whether via sqlplus or the same cursor, I get the following error:
Error starting at line 1 in command:
INSERT INTO AUDIT_LOG (LOG_DBID,USER_NAME,EVENT_DATE,SEVERITY) VALUES ('AUDIT_LOG_SQ.nextval', 'SYSTEM#do',datetime.datetime(2018, 4, 28, 1, 57, 42), '1')
Error at Command Line:1 Column:95
Error report:
SQL Error: ORA-00904: "DATETIME"."DATETIME": invalid identifier
00904. 00000 - "%s: invalid identifier"
Without the datetime element the queries work just fine.
How do I insert a result I got from a cursor?
I checked SQL_Developer exports to compare with mine, and they have a different way of handling it:
INSERT INTO AUDIT_LOG (LOG_DBID,USER_NAME,EVENT_DATE,SEVERITY) VALUES ('AUDIT_LOG_SQ.nextval', 'user#do',to_timestamp('25-APR-18','DD-MON-RR HH.MI.SSXFF AM'), '1')
Which I haven't really found a way to duplicate (without turning the whole query into an ugly string concatenation), and I'm not sure I need to - there must be something I'm missing!
Any help would be appreciated, thanks!
I don't know how to do what you're doing, but - as for 5 hours there are no answers, let me say a word or two.
This is a statement that failed:
INSERT INTO AUDIT_LOG (LOG_DBID,USER_NAME,EVENT_DATE,SEVERITY) VALUES
('AUDIT_LOG_SQ.nextval', 'SYSTEM#do',datetime.datetime(2018, 4, 28, 1, 57, 42), '1')
What do you expect datetime.datetime to be? To me (and, presumably, Oracle), it looks as if it there's user whose name is datetime (the first one, in front of the dot) which has a function named datetime (the second one, behind the dot). Most probably neither of these two is true, is it?
I'd suggest you to try with the TO_DATE function which would accept two parameters: date (and time) and appropriate format mask, such as
to_date('2018-04-28 01:57:42', 'yyyy-mm-dd hh24:mi:ss')
You'd put that instead of your datetime construct.
However, I'm afraid that - even if you do that - INSERT might fail once again because of the first value you're inserting.
LOG_DBID looks like an ID (NUMBER datatype); is it? INSERT you wrote is trying to insert a string into it - because you enclosed it into single quotes: 'audit_log_sq.nextval'. AUDIT_LOG_SQ is a sequence name. So, if you want to insert a numeric value into that column, you should omit single quotes.
Finally, statement that might work (at least, in Oracle itself) would look like this:
INSERT INTO AUDIT_LOG (LOG_DBID,USER_NAME,EVENT_DATE,SEVERITY) VALUES
(AUDIT_LOG_SQ.nextval,
'SYSTEM#do',
to_date('2018-04-28 01:57:42', 'yyyy-mm-dd hh24:mi:ss'),
'1')
I hope it makes sense, even in your context.
SQL Error: ORA-00904: "DATETIME"."DATETIME": invalid identifier
You get this error because datetime.datetime is not valid Oracle syntax. You sort of know that, because you know how Oracle SQL Developer formats timestamps. But you're don't want to replicate the explicit to_timestamp() logic.
It's not clear to me where you're getting the values of EVENT_DATE from, but given that this is an audit function maybe what you need is sysdate , an Oracle built-in which gives us the current date and time.

Error converting data type varchar to numeric. SQL Server INSERT statement

I am trying to insert some data into this table, but I get this error:
Msg 8114, Level 16, State 5, Line 3
Error converting data type varchar to numeric.
I tried to remove the quotes, but it is still showing me the same error:
USE CobornSalesDB;
GO
INSERT INTO SalesActivity
VALUES ('AC00001', '05-12-2016', 'AG16170', 'C000001', 'P0001', 'S00002'‌​, '1', '200000.00', '',‌ ​'1.2220', '20', '100000.00', '25-12-2016', '30-12-2016', '31-12-2016', 'A00‌​0001', 'PR00001');
GO
In all of your numeric columns, take the commas out of the values you are inserting.
This is your query taken from the comment.
You really should include it in the question as text, not as image.
INSERT INTO SalesActivity VALUES
('AC00001',
'05-12-2016',
'AG16170',
'C000001',
'P0001',
'S00002'‌​,
'1',
'200000.00',
'',‌ -- valueEUR
​'1.2220',
'20',
'100000.00',
'25-12-2016',
'30-12-2016',
'31-12-2016',
'A00‌​0001',
'PR00001');
In the definition of the table we can see that valueEUR column is numeric. You are passing a string there. Not just a string, but a string that can not be converted into a number. An empty string '' can't be converted into a number.
I'm guessing, you want to insert NULL in that field. So, you should
write NULL in the INSERT statement.
Also, you should remove all quotes around numbers, so that the server would not have to convert strings into numbers.
Also, you should write your dates in YYYY-MM-DD format. Otherwise, one day you may be surprised to see that server guessed it incorrectly and swapped month and day.
Also, you should list all column names in the INSERT statement. Otherwise your code will break when you add a new column to the table.
The query should look similar to this:
INSERT INTO dbo.SalesActivity
(Activity_ID,
[Date],
Quatation_Number,
Customer_ID,
Product_ID,
Status_ID,
Quantity,
valueGBR,
valueEUR,
Rate,
Commission,
weightedValue,
estDecisionDate,
currentEstCompletionDate,
originalEstCompletionDate,
Agent_ID,
Probability_ID)
VALUES
('AC00001',
'2016-12-05',
'AG16170',
'C000001',
'P0001',
'S00002'‌​,
1,
200000.00,
NULL,‌
​1.2220,
20,
100000.00,
'2016-12-25',
'2016-12-30',
'2016-12-31',
'A00‌​0001',
'PR00001');
Try entering date in mm/dd/yyyy format like this
INSERT INTO SalesActivity VALUES ('AC00001','12-05-2016','AG16170','C000001',
'P0001','S00002'‌​,1,200000.00,'',‌ ​1.2220, 20,100000.00,
'12-25-2016','12-30-2016','12-31-2016','A00‌​0001','PR00001');

Error Inserting values in Dreamer Table

I'm sorry if this is a simple question but I'm rather new to SQL and I'm having an issue trying to insert some values in a table.
The query I'm executing is the following:
INSERT INTO Dreamer VALUES (
'', 'Dreamer name', '0', '1554542121', 'pablogardiazabal#gmail.com',
'Dreamer FB', 'Dreamer TW', 'Dreamer', 'M', '', 0, 0, 'Dreamer DAD',
'Dreamer MOM', '0', '0', '151515131321', '545343512123',
'DreamerDAD#daddreamer.com', 'DreamerMOM#momdreamer.com',
'Dreamer DAD DIR', 'Dreamer MOM DIR', '1515312123123',
'5456453423', 0)
And the table is designed like this:
TABLE This is the Table
Thanks a lot guys and gals!
EDITTED (sorry about the wrong format)
The error I'm getting is the following
Msg 8152, Level 16, State 14, Line 1
String or binary data would be truncated.
The statement has been terminated.
There is mismatch in your order of values, It is better to provide your insert script along with column names and corresponding values as below:
INSERT INTO Dreamer (col1, col2...) VALUES (val1,val2...)
There is no shortcut to doing the dirty work of comparing every string value in your select list with the definition of the associated column. And you REALLY need to learn how to write literials of a given datatype. '' is not really a valid integer - if you want zero than use the correct literal. And the integer zero is not the same as NULL. Do not start using a bad habit of equating special values with NULL - it will eventually bite you.
The first problem I see is '151515131321' - which is to be assigned to the column DocNumberP : varchar(10). That is more than 10 characters.

How to CONCAT quotes while selecting any data from the table

The file (date.sql) has the below commands
date=2014-12-03
SET VAR vDate $date
insert into (Some_table) (date,location)
select $vDate , location from (let say from table "Location")
while executing this sql script i am getting the below error as its expecting values like '2014-12-03' but here its coming without quotes
ERROR:Insert data type mismatch for column date
Is there anyway to concat ' before and after date or is there any simpler way to achieve it ???
Thanks in advance.

PL/SQL Oracle hintless error

I'm programming a function in a Oracle using the SQL Dveloper IDE.
The function works just fine, and when I add this statement:
INSERT INTO bl_transaction
VALUES(generated_id,'0','0','Y',NOW(),'0',NOW(),'0',CAST(dbms_random.value(100,100000) as integer), tuple.billing_id, tuple.created, sys_guid(), first_invgroup, 'Y', 'N', tuple.guid, NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
The compiler give me a hintless error:
ORA-06553: PLS-320: the declaration of the type of this expression is incomplete or malformed
I have reviewed every possible type mismatch, number of arguments, etc.
How can I resolve this?
NOW() isn't a supported Oracle function to get the current date & time -- SYSDATE is. Try:
INSERT INTO bl_transaction
VALUES(generated_id,'0','0','Y',SYSDATE,'0',SYSDATE,'0',CAST(dbms_random.value(100,100000) as integer), tuple.billing_id, tuple.created, sys_guid(), first_invgroup, 'Y', 'N', tuple.guid, NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
But you also have:
tuple.created
tuple.billing_id
...as values but didn't include where these are coming from.
Third, because you didn't provide a list of the columns being inserted into, we have no way of knowing if your query specifies more or less that the number of columns in the table your attempting to insert into... or an insight into the data types at each position.