As the title says, how am I going to deal with a column name in FBExport that look like a keyword?
this is how my statement looks like:
-Q "SELECT a.ID, a.USERID, a.`WHEN`, a.INOUT FROM ATTENDANT a"
then I get this error:
Engine Code : 335544569
Engine Message :
Dynamic SQL Error
SQL error code = -104
Token unknown - line 1, column 26
WHEN
When I use
"WHEN"
Error: Switches must begin with -
tried 'When'
-Q "SELECT a.ID, a.USERID, a.'WHEN', a.INOUT FROM ATTENDANT a;"
SQL Message : -104
Invalid token
Engine Code : 335544569
Engine Message :
Dynamic SQL Error
SQL error code = -104
Token unknown - line 1, column 26
'WHEN'
Error: Switches must begin with -
What are the correct escape characters?
For dialect 3 database, Firebird allows quoting object names using double quotes ("<objectname>"). Be aware that quoting object names makes them case sensitive, so "WHEN" is not the same as "when". If your database is dialect 1 then this is not possible, and you should first convert your database to dialect 3.
However the problem this is a command line option, meaning that
-Q "SELECT a.ID, a.USERID, a."WHEN", a.INOUT FROM ATTENDANT a"
Is split by your shell to the arguments:
-Q
SELECT a.ID, a.USERID, a.
WHEN
, a.INOUT FROM ATTENDANT a
While you want:
-Q
SELECT a.ID, a.USERID, a."WHEN", a.INOUT FROM ATTENDANT a
To achieve that, you need to escape the double quote inside the second argument, so:
-Q "SELECT a.ID, a.USERID, a.\"WHEN\", a.INOUT FROM ATTENDANT a"
or - as indicated by a_horse_with_no_name in the comments - wrap the argument in single quotes:
-Q 'SELECT a.ID, a.USERID, a."WHEN", a.INOUT FROM ATTENDANT a'
This doesn't really have to do with Firebird or FBExport, but is a result of how your shell (eg bash) parses commandline arguments.
It looks like someone else is dealing with the external access to the Firebird database from Safescan TimeAttenedant
It was a little bit stupid from Safescan to name a column WHEN because this is a keyword in Firebird.
In the context of an insert statement, I have no success with a column list like:
insert into attendant (ID, USERID, DEVICEID, WHEN, INOUT, VERIFYMODE, WORKCODE) values (1092, 1, 1, '28.08.2017 08:00', 0, 4, 3);
"WHEN", \"WHEN\", \'WHEN\', ... no success
Remedy - Insert all data without column list, ex:
insert into attendant values (1034, 2, 1, '28.08.2017 08:00', 0, 4, null, null, null, null, null, 3);
Query is much easier: select * from attendant;
Related
I am using DB2 LUW and want to a assign a result of a With clause to a variable in a stored procedure.
I got the exception
{0:0} An unexpected token "AS" was found following "l = (WITH BASE". Expected tokens may include: "JOIN".. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.28.11
Is it possible to assign the result on this way or should I have to solve it with a cursor?
DECLARE result CLOB(8M);
SET result = (WITH BASE AS (
xxx
)
SELECT JSON_ARRAY (select json_objects FROM ITEMS format json) FROM SYSIBM.SYSDUMMY1);
Use instead the syntax style:
with ctename AS ( ... ) SELECT ... INTO ... FROM ctename;
I have this table in postgres
CREATE TABLE target (
a json
b integer
c text []
id integer
CONSTRAINT id_fkey FOREIGN KEY (id)
REFERENCES public.other_table(id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION,
)
Which I would like to insert data to from psycopg2 using
import psycopg2
import psycopg2.extras as extras
# data is of the form dict, integer, list(string), string <- used to get fkey id
data = [[extras.Json([{'a':1,'b':2}, {'d':3,'e':2}]), 1, ['hello', 'world'], 'ident1'],
[extras.Json([{'a':4,'b':3}, {'d':1,'e':9}]), 5, ['hello2', 'world2'], 'ident2']]
# convert data to list of tuples containing objects
x = [tuple(u) for u in data]
# insert data to the database
query = ('WITH ins (a, b, c, ident) AS '
'(VALUES %s) '
'INSERT INTO target (a, b, c, id) '
'SELECT '
'ins.a '
'ins.b '
'ins.c '
'other_table.id'
'FROM '
'ins '
'LEFT JOIN other_table ON ins.ident = other_table.ident;')
cursor = conn.cursor()
extras.execute_values(cursor, query, x)
When I run this I get the error: column "a" is of type json but expression is of type text. I tried to solve this by adding a type cast in the SELECT statement but then I got the same error for c and then for b.
Originally I thought the problem lies in the WITH statement but based on the answers to my previous question this seems to not be the case Postgres `WITH ins AS ...` casting everything as text
It seems that execute_values is sending all the values as text with ' '.
Main Question: How can I get execute_values to send the values based on their python data type rather than just as text?
Sub questions:
How can I confirm that execute_values is in fact sending the values as text with quotation marks?
What is the purpose of the template argument of execute_values https://www.psycopg.org/docs/extras.html and could that be of help?
The issue, as Adrian Klaver points out in their comment, and also seen in this answer, is that the typing is lost in the CTE.
We can show this with an example in the psql shell:
CREATE TABLE test (col1 json);
WITH cte (c) AS (VALUES ('{"a": 1}'))
INSERT INTO test (col) SELECT c FROM cte;
resulting in
ERROR: column "col" is of type json but expression is of type text
whereas this version, with the type specified, succeeds:
WITH cte(c) AS (VALUES ('{"a": 1}'::json))
INSERT INTO test (col) SELECT c FROM cte;
We can mimic this in execute_valuesby providing the typing information in the template argument:
extras.execute_values(cursor, query, data, template='(%s::json, %s, %s, %s)')
I have a SQL query which takes user inputs hence security flaw is present.
The existing query is:
SELECT BUS_NM, STR_ADDR_1, CITY_NM, STATE_CD, POSTAL_CD, COUNTRY_CD,
BUS_PHONE_NB,PEG_ACCOUNT_ID, GDN_ALERT_ID, GBIN, GDN_MON_REF_NB,
ALERT_DT, ALERT_TYPE, ALERT_DESC,ALERT_PRIORITY
FROM ( SELECT A.BUS_NM, AE.STR_ADDR_1, A.CITY_NM, A.STATE_CD, A.POSTAL_CD,
CC.COUNTRY_CD, A.BUS_PHONE_NB, A.PEG_ACCOUNT_ID, 'I' ||
LPAD(INTL_ALERT_DTL_ID, 9,'0') GDN_ALERT_ID,
LPAD(IA.GBIN, 9,'0') GBIN, IA.GDN_MON_REF_NB,
DATE(IAD.ALERT_TS) ALERT_DT,
XMLCAST(XMLQUERY('$A/alertTypeConfig/biqCode/text()' passing
IAC.INTL_ALERT_TYPE_CONFIG as "A") AS CHAR(4)) ALERT_TYPE,
, ROW_NUMBER() OVER () AS "RN"
FROM ACCOUNT A, Other tables
WHERE IA.GDN_MON_REF_NB = '100'
AND A.PEG_ACCOUNT_ID = IAAR.PEG_ACCOUNT_ID
AND CC.COUNTRY_CD = A.COUNTRY_ISO3_CD
ORDER BY IA.INTL_ALERT_ID ASC )
WHERE ALERT_TYPE IN (" +TriggerType+ ");
I changed it to accept TriggerType from setString like:
SELECT BUS_NM, STR_ADDR_1, CITY_NM, STATE_CD, POSTAL_CD, COUNTRY_CD,
BUS_PHONE_NB,PEG_ACCOUNT_ID, GDN_ALERT_ID, GBIN, GDN_MON_REF_NB,
ALERT_DT, ALERT_TYPE, ALERT_DESC,ALERT_PRIORITY
FROM ( SELECT A.BUS_NM, AE.STR_ADDR_1, A.CITY_NM, A.STATE_CD, A.POSTAL_CD,
CC.COUNTRY_CD, A.BUS_PHONE_NB, A.PEG_ACCOUNT_ID,
'I' || LPAD(INTL_ALERT_DTL_ID, 9,'0') GDN_ALERT_ID,
LPAD(IA.GBIN, 9,'0') GBIN, IA.GDN_MON_REF_NB,
DATE(IAD.ALERT_TS) ALERT_DT,
XMLCAST(XMLQUERY('$A/alertTypeConfig/biqCode/text()' passing
IAC.INTL_ALERT_TYPE_CONFIG as "A") AS CHAR(4)) ALERT_TYPE,
ROW_NUMBER() OVER () AS "RN"
FROM ACCOUNT A, other tables
WHERE IA.GDN_MON_REF_NB = '100'
AND A.PEG_ACCOUNT_ID = IAAR.PEG_ACCOUNT_ID
AND CC.COUNTRY_CD = A.COUNTRY_ISO3_CD
ORDER BY IA.INTL_ALERT_ID ASC )
WHERE ALERT_TYPE IN (?);
Setting trigger type as below:
if (StringUtils.isNotBlank(request.getTriggerType())) {
preparedStatement.setString(1, triggerType != null ? triggerType.toString() : "");
}
Getting error as
Caused by: com.ibm.db2.jcc.am.SqlDataException: DB2 SQL Error: SQLCODE=-302, SQLSTATE=22001, SQLERRMC=null, DRIVER=4.19.26
The -302 SQLCODE indicates a conversion error of some sort.
SQLSTATE 22001 narrows that down a bit by telling us that you are trying to force a big string into a small variable. Given the limited information in your question, I am guessing it is the XMLCAST that is the culprit.
DB2 won't jam 30 pounds of crap into a 4 pound bag so to speak, it gives you an error. Maybe giving XML some extra room in the cast might be a help. If you need to make sure it ends up being only 4 characters long, you could explicitly do a LEFT(XMLCAST( ... AS VARCHAR(64)), 4). That way the XMLCAST has the space it needs, but you cut it back to fit your variable on the fetch.
The other thing could be that the variable being passed to the parameter marker is too long. DB2 will guess the type and length based on the length of ALERT_TYPE. Note that you can only pass a single value through a parameter marker. If you pass a comma separated list, it will not behave as expected (unless you expect ALERT_TYPE to also contain a comma separated list). If you are getting the comma separated list from a table, you can use a sub-select instead.
Wrong IN predicate use with a parameter.
Do not expect that IN ('AAAA, M250, ABCD') (as you try to do passing a comma-separated string as a single parameter) works as IN ('AAAA', 'M250', 'ABCD') (as you need). These predicates are not equivalent.
You need some "string tokenizer", if you want to pass such a comma-separated string like below.
select t.*
from
(
select XMLCAST(XMLQUERY('$A/alertTypeConfig/biqCode/text()' passing IAC.INTL_ALERT_TYPE_CONFIG as "A") AS CHAR(4)) ALERT_TYPE
from table(values xmlparse(document '<alertTypeConfig><biqCode>M250, really big code</biqCode></alertTypeConfig>')) IAC(INTL_ALERT_TYPE_CONFIG)
) t
--WHERE ALERT_TYPE IN ('AAAA, M250, ABCD')
join xmltable('for $id in tokenize($s, ",\s?") return <i>{string($id)}</i>'
passing cast('AAA, M250 , ABCD' as varchar(200)) as "s"
columns token varchar(200) path '.') x on x.token=t.ALERT_TYPE
;
Run the statement as is. Then you may uncomment the string with WHERE clause and comment out the rest to see what you try to do.
P.S.:
The error you get is probably because you don't specify the data type of the parameter (you don't use something like IN (cast(? as varchar(xxx))), and db2 compiler assumes that its length is equal to the length of the ALERT_TYPE expression (4 bytes).
EXECUTE 'select to_char(application_date::timestamp, 'Mon-YY') as appl_month from my_schema.my_table;';
The above PostgreSQL EXECUTE statement is giving the below error:
ERROR: syntax error at or near "'select
to_char(application_date::timestamp, '" LINE 1: EXECUTE 'select
to_char(application_date::timestamp, 'Mon-YY...
^
********** Error **********
ERROR: syntax error at or near "'select
to_char(application_date::timestamp, '" SQL state: 42601 Character: 9
Any suggestions will be helpful.
Changed to below statement
EXECUTE 'select to_char(application_date::timestamp, ' || quote_literal(Mon-YY) || ') from standard.npo_weekly_export;';
But giving new error:
ERROR: syntax error at or near "'select to_char(application_date::timestamp, '"
LINE 1: EXECUTE 'select to_char(application_date::timestamp, ' || qu...
^
********** Error **********
ERROR: syntax error at or near "'select to_char(application_date::timestamp, '"
SQL state: 42601
Character: 9
Expected Output: - Counts by month in Mon-YY format
Application month Application # Final Approval #
Jan-17 1,000 800
Feb-17 1,010 808
Mar-17 1,020 816
Apr-17 1,030 824
If I do the below query:
select to_char(application_date, 'Mon-YY') as appl_month,
count(distinct application_id) as appl_count,
sum(final_approval_ind) as fa_count,
from my_schema.my_table
group by appl_month
order by appl_month;
Generated output: (Note: Sorted by text, not by date)
"Apr-17";94374;19953
"Apr-18";87446;20903
"Aug-17";102043;21536
"Aug-18";91107;20386
"Dec-17";63263;13755
"Dec-18";21358;74
"Feb-17";89447;18084
"Feb-18";75426;16144
"Jan-17";86103;16394
"Jan-18";79403;17766
"Jul-17";90380;18929
"Jul-18";85439;20186
"Jun-17";95596;20403
"Jun-18";85764;18707
"Mar-17";112929;23323
"Mar-18";91179;21841
"May-17";101907;22349
"May-18";90885;21550
"Nov-17";78284;16791
"Nov-18";80472;7656
"Oct-17";87955;18524
"Oct-18";82821;17056
"Sep-17";80740;17788
"Sep-18";75785;18009
Problem: to_char() returns text and it sorts by text and not by date. So the output is jumbled rather than sorted by Mon-YY.
Do the aggregation in a derived table (aka "sub-query") that preserves the data type, then do the sorting in the outer query:
select to_char(ap_month, 'Mon-YY') as appl_month
appl_count,
fa_count
from (
select date_trunc('month', application_date) as ap_month,
count(distinct application_id) as appl_count,
sum(final_approval_ind) as fa_count,
from my_schema.my_table
group by ap_month
) t
order by ap_month;
date_trunc('month', application_date) will normalize the application_date to the start of the month, but will retain the date data type, so that the sorting in the outer query works correctly.
I have no idea what the dynamic SQL in your question is supposed to do, but if you need to use that query for whatever reasons as dynamic SQL, you need to escape the single quotes by doubling them.
execute '
select to_char(ap_month, ''Mon-YY'') as appl_month
appl_count,
fa_count
from (
select date_trunc(''month'', application_date) as ap_month,
count(distinct application_id) as appl_count,
sum(final_approval_ind) as fa_count,
from my_schema.my_table
group by ap_month
) t
order by ap_month;
'; -- end of dynamic SQL
But using Postgres' dollar quoting would be easier:
execute $dyn$
select to_char(ap_month, 'Mon-YY') as appl_month
appl_count,
fa_count
from (
select date_trunc('month', application_date) as ap_month,
count(distinct application_id) as appl_count,
sum(final_approval_ind) as fa_count,
from my_schema.my_table
group by ap_month
) t
order by ap_month;
$dyn$; -- end of dynamic SQL
Note that you can nest dollar quoted strings, so if that query is used inside a function, just use a different delimiter than you use for the function body (see the example in the manual)
When I use cache sql query in C# I'm getting an error:
SQLtext1 = "SELECT top 10 * FROM dbo.DAPPLICATIONSTAT where TIMESTAMP = '2015-02-01 00:00:00'"
I would like to use a where clause with a datetime filter.
I am using InterSystems.Data.CacheClient.dll to execute the query.
Error Messge :
[SQLCODE: <-4>:<A term expected, beginning with one of the following: identifier, constant, aggregate, %ALPHAUP, %EXACT, %MVR, %SQLSTRING, %SQLUPPER, %STRING, %UPPER, $$, :, +, -, (, NOT, EXISTS, or FOR>]
[Cache Error: <<SYNTAX>errdone+2^%qaqqt>] [Details: <Prepare>]
[%msg: < SQL ERROR #4: A term expected, beginning with either of: (, NOT, EXISTS, or FOR^SELECT top :%qpar(1) * FROM dbo . DAPPLICATIONSTAT where TIMESTAMP>
I think that you have reserved word TIMESTAMP and so, you have that error
Try this SQL query, where filedname TIMESTAMP in dobled quotas
SELECT top 10 * FROM dbo.DAPPLICATIONSTAT where "TIMESTAMP" = '2015-02-01 00:00:00'