USING CAST STATEMENT IN INSERT INTO STATEMENT SQL - sql

Below (1) is the query which I wrote and when I am not using CAST i am getting error (2) and when am using cast its throwing another syntax error(3)
(1)
/*DROP TABLE IF EXISTS LFB1_BACKUPTABLE
CREATE TABLE LFB1_BACKUPTABLE AS
(SELECT * FROM LFB1);
*/
INSERT INTO LFB1_BACKUPTABLE (
MANDT,LIFNR,BUKRS,PERNR,ERDAT,ERNAM,SPERR,LOEVM,ZUAWA,
AKONT,BEGRU,VZSKZ,ZWELS,XVERR,ZAHLS,ZTERM,EIKTO,ZSABE,
KVERM,FDGRV,BUSAB,LNRZE,LNRZB,ZINDT,ZINRT,DATLZ,XDEZV,
WEBTR,KULTG,REPRF,TOGRU,HBKID,XPORE,QSZNR,QSZDT,QSSKZ,
BLNKZ,MINDK,ALTKN,ZGRUP,MGRUP,UZAWE,QSREC,QSBGR,QLAND,
XEDIP,FRGRP,TOGRR,TLFXS,INTAD,XLFZB,GUZTE,GRICD,GRIDT,
XAUSZ,CERDT,CONFS,UPDAT,UPTIM,NODEL,TLFNS,AVSND,AD_HASH,
J_SC_SUBCONTYPE,J_SC_COMPDATE,J_SC_OFFSM,J_SC_OFFSR,
BASIS_PNT,GMVKZK,PREPAY_RELEVANT,ASSIGN_TEST, CAST(_CELONIS_CHANGE_DATE AS DATE) AS _CELONIS_CHANGE_DATE
)
SELECT DISTINCT * FROM LFB1
WHERE MANDT||LIFNR||BUKRS NOT IN (SELECT DISTINCT MANDT||LIFNR||BUKRS FROM
LFB1_BACKUPTABLE);
(2) Execution error:
[Vertica]VJDBC ERROR: Column "_CELONIS_CHANGE_DATE" is of type timestamptz but expression is of type varchar
(3) Execution error:
[Vertica]VJDBC ERROR: Syntax error at or near "CAST"

Why are you using a cast statement in your insert table column list? You can't change the type of the destination table columns.
You need to change the type of the values you are inserting.
INSERT INTO LFB1_BACKUPTABLE (
MANDT,LIFNR,BUKRS,PERNR,ERDAT,ERNAM,SPERR,LOEVM,ZUAWA,
AKONT,BEGRU,VZSKZ,ZWELS,XVERR,ZAHLS,ZTERM,EIKTO,ZSABE,
KVERM,FDGRV,BUSAB,LNRZE,LNRZB,ZINDT,ZINRT,DATLZ,XDEZV,
WEBTR,KULTG,REPRF,TOGRU,HBKID,XPORE,QSZNR,QSZDT,QSSKZ,
BLNKZ,MINDK,ALTKN,ZGRUP,MGRUP,UZAWE,QSREC,QSBGR,QLAND,
XEDIP,FRGRP,TOGRR,TLFXS,INTAD,XLFZB,GUZTE,GRICD,GRIDT,
XAUSZ,CERDT,CONFS,UPDAT,UPTIM,NODEL,TLFNS,AVSND,AD_HASH,
J_SC_SUBCONTYPE,J_SC_COMPDATE,J_SC_OFFSM,J_SC_OFFSR,
BASIS_PNT,GMVKZK,PREPAY_RELEVANT,ASSIGN_TEST, _CELONIS_CHANGE_DATE
)
SELECT DISTINCT col1, col2, col3, ..., timestamp_col::DATE FROM LFB1
WHERE MANDT||LIFNR||BUKRS NOT IN (SELECT DISTINCT MANDT||LIFNR||BUKRS FROM LFB1_BACKUPTABLE);
Your syntax for casting to a date is syntactically correct, but in this example I used the more common Vertica syntax which is col::DATE, both will work.

Related

SELECT throwing an CAST error on a row that does not exist in query

I'm having a problem with a SELECT that is throwing a CAST error, but only when the CAST is in the WHERE clause. I've boiled the problem down to the below example SQL.
CREATE TABLE dbo.CastTest (
[WhatIsThis] nvarchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL)
GO
INSERT INTO dbo.CastTest (WhatIsThis) VALUES ('NotANumber');
INSERT INTO dbo.CastTest (WhatIsThis) VALUES ('11');
INSERT INTO dbo.CastTest (WhatIsThis) VALUES ('4');
SELECT *, CAST(WhatIsThis AS INT) ANumber
FROM (
SELECT * FROM dbo.CastTest WHERE ISNUMERIC(WhatIsThis)=1
) OnlyNumbers
-- WHERE CAST(WhatIsThis AS INT)>10
The code above works, returning two rows where the NVARCHAR is CAST to a number, and excludes the other row where it is not a number. But as soon as you uncomment the WHERE clause you get the following;
Conversion failed when converting the nvarchar value 'NotANumber' to data type int.
Why is the CAST failing on a row that should not be visible to it? What can I do to avoid this error?
Don't use isnumeric() for this purpose. SQL in general does not guarantee the order of evaluation of clauses. This includes subqueries and CTEs. The operations can all be rearranged (and often are).
Instead, use try_convert() or try_cast() with an explicit conversion:
SELECT *, TRY_CAST(WhatIsThis AS INT) as ANumber
FROM (SELECT *
FROM dbo.CastTest
WHERE TRY_CONVERT(int, WhatIsThis) IS NOT NULL
) OnlyNumbers

How to insert table in Databricks using magic SQL operator

I have create the following SQL table in databricks (using the magic %sql) as follows:
%sql
CREATE TABLE mytable (
id INT
,name STRING
,met_area_name STRING
,state STRING
,type STRING
) USING CSV
I am now trying insert data into the table using the following command:
%sql
INSERT INTO TABLE mytable VALUES (id,name,type)
SELECT DISTINCT criteria1, criteria2, 'b'
FROM tablex
WHERE somecriteria1 = 0
ORDER BY somecriteria2;
However, I'm getting the following error:
Error in SQL statement: ParseException:
mismatched input 'FROM' expecting <EOF>(line 2, pos 2)
== SQL ==
INSERT INTO TABLE mytable VALUES (id,name,type)
FROM tablex
--^^^
WHERE somecriteria1 = 0
ORDER BY somecriteria2
I'm sure there is something very obvious that I'm missing, but I can't see it.
Any assistance much appreciated.
Cheers

How to save query result when using SQL in R?

If just SQL, we can use the following code to save a query result in a temporary table, so that we can use the result later.
CREATE TABLE #TEMPTABLE
(
Column1 type1,
Column2 type2,
Column3 type3
)
INSERT INTO #TEMPTABLE
SELECT ...
SELECT *
FROM #TEMPTABLE ...
This answer is from How to save select query results within temporary table?
However, I am using R to connect HANA. I need to use SQL query in R to select data from HANA. I need a tempory table for my query result. My code is like this:
sqlQuery(ch,paste('
CREATE TABLE #myTemp(
"/BIC/ZSALE_OFF" INT
)
INSERT INTO #myTemp
SELECT
"/BIC/ZSALE_OFF"
FROM
"SAPB1D"."/BIC/AZ_RT_A212"
'))
I have got the following error information:
[1] "42000 257 [SAP AG][LIBODBCHDB DLL][HDBODBC] Syntax error or access violation;257 sql syntax error: incorrect syntax near \"INSERT\": line 5 col 19 (at pos 124)"
[2] "[RODBC] ERROR: Could not SQLExecDirect '\n CREATE TABLE #myTemp(\n \"/BIC/ZSALE_OFF\" INT\n )\n INSERT INTO #myTemp\n SELECT\n \"/BIC/ZSALE_OFF\"\n FROM\n \"SAPB1D\".\"/BIC/AZ_RT_A212\"\n
Without the temperory result part, the code for just query is correct:
sqlQuery(ch,paste('
SELECT
"/BIC/ZSALE_OFF"
FROM
"SAPB1D"."/BIC/AZ_RT_A212"
'))
I am not sure if the grammar is correct, or there is something else I do not understand.

UNION ALL two SELECTs with different column types - expected behaviour?

What is the expected behaviour due to SQL Standard when we perform UNION on two tables with different data types:
create table "tab1" ("c1" varchar(max));
create table "tab2" ("c3" integer);
insert into tab1 values(N'asd'), (N'qweqwe');
insert into tab2 values(123), (345);
select
c_newname as myname
from
(
select "c1" as c_newname from "tab1"
union all
select "c3" from "tab2"
) as T_UNI;
MS SQL Server gives
Conversion failed when converting the varchar value 'asd' to data type
int.
but what is defined in the standard?
From T-SQL UNION page:
The following are basic rules for combining the result sets of two
queries by using UNION:
The number and the order of the columns must be the same in all queries.
The data types must be compatible.
When one datatype is VARCHAR and other is INTEGER then SQL Server will implicitly attempt to convert VARCHAR to INTEGER (the rules are described in the precedence table). If conversion fails for any row, the query fails. So this works:
INSERT INTO #tab1 VALUES(N'123'), (N'345');
INSERT INTO #tab2 VALUES(123), (345);
SELECT C1 FROM #tab1 UNION ALL SELECT C2 FROM #tab2
But this does not:
INSERT INTO #tab1 VALUES(N'ABC'), (N'345');
INSERT INTO #tab2 VALUES(123), (345);
SELECT C1 FROM #tab1 UNION ALL SELECT C2 FROM #tab2
-- Conversion failed when converting the varchar value 'ABC' to data type int.
The rules for conversion are described here:
T-SQL Data Type Precedence
Having said that, you can explicitly convert your integer data to varchar in order to make the query work (the datatype of result would be varchar).
If you want to use union all columns in every query need to have the same type.C3 must be converteted to varchar because c1 is varchar. Try below solution
create table "tab1" ("c1" varchar(max));
create table "tab2" ("c3" integer);
insert into tab1 values(N'asd'), (N'qweqwe');
insert into tab2 values(123), (345);
select
c_newname as myname
from
(
select "c1" as c_newname from "tab1"
union all
select cast("c3" as varchar(max)) from "tab2"
) as T_UNI;
I replaced "tab3" with "tab1" - I think it's typo.
The basic rule is-->
Either the datatype used should be same in two table(or)you should use cast or convert function to match the datatypes in those two tables.
SQL Standard:
1)The number and the order of the columns must be the same in all queries.
2)Column datatypes must be compatible: They need not be the same exact same type, but they must be of a type that SQL Server can implicitly convert.

How to retrieve data from Table-Function in DB2

I have a Table Function it return a table of (student_id,student_name)
I want to call it and insert the result into another table
I use
INSERT INTO STUDENT_TMP SELECT Table(MyDB.fn_getStudent())
but i did not get the result
I have got an error :
ERROR: DB2 SQL Error: SQLCODE=-390, SQLSTATE=42887,
SQLERRMC=MyDB.AA;SQL131208155041300,DRIVER=3.67.26
Error Code: -390
I found the followin exsample on ibm sites:
select t1.timeid, t1.storeid, t1.sales
from time, store, table (cvsample.salesfunc(time.timeid, store.storeid)) as t1
where time.timeid = t1.timeid and store.storeid = t1.storeid;
notice the syntax: table (cvsample.salesfunc(time.timeid, store.storeid)) as t1
so you prob dont need fields and 'as' you still need '*' and the 'FROM'
so
INSERT INTO STUDENT_TMP SELECT * FROM Table (MyDB.fn_getStudent())