MariaDB SQL syntax error with Output file Concatenation - mariadb

What am I doing wrong here at line 7? Can't seem to figure this one out. Anyone willing to help? Thanks
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
near '11:29:08' at line 7
Line 7
FIELDS TERMINATED BY ','
SET #sql_text =
CONCAT (
"SELECT price_id, customer, location, tier, channel_segment, product, best_before_date, brand, pack, price, tonnes, date_reported, created_at, week
INTO OUTFILE 'C:/Temp/price_data_"
, DATE_FORMAT( NOW(), '%Y%m%d')
, ".csv'
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
FROM price_data_summary
WHERE date_reported >=", now()-interval 3 month);
PREPARE s1 FROM #sql_text;
EXECUTE s1;
DROP PREPARE s1;

Related

MYSQL Update errors

Getting errors on the following. seems simple, but can't clear this error:
NOTE: that wphz_posts.guid is a text field, not int
All table and column names are correct
"SQL Error (1064): You have an error in your SQL syntax; ‘check the
manual that corresponds to your MariaDB server version for the right
syntax to use near ' WHERE wphz_postmeta.meta key = ‘ProductURL’ AND
wphz_postmeta.post id = wphz.. at line 3
UPDATE wphz_posts
SET wphz_posts.guid = (select concat(wphz_postmeta.meta_value,"?campid=nnnnnn")
WHERE wphz_postmeta.meta_key = 'ProductURL' AND wphz_postmeta.post_id = wphz_posts.id)

How to resolve ORA-01489: result of string concatenation is too long [duplicate]

This question already has an answer here:
Create Pivot view in SQL from a SQL table
(1 answer)
Closed 2 years ago.
I have a table temp and Im trying to query as below :
SELECT
LISTAGG( 'MAX(CASE WHEN CATEGORY = '''||CATEGORY||''' THEN "'||"LEVEL"||'" END) AS "'||
"LEVEL"||'_'||CATEGORY||'"' , ',' ) WITHIN GROUP ( ORDER BY CATEGORY, "LEVEL" DESC
) AS col2
FROM
(
SELECT DISTINCT
"LEVEL",
CATEGORY
FROM
TEMP );
`
I get error as [Code: 1489, SQL State: 72000] ORA-01489: result of string concatenation is too long
Im unable to get rid of this error.
I'm using SQL Commander of DBVisualizer .
I also tried to declare variable before but it does not seem to work:
#ECHO ${col2 ||32767||varchar2}$
I tried to ALTER SYSTEM SET MAX_STRING_SIZE = EXTENDED; which is also giving error : [Code: 2065, SQL State: 42000] ORA-02065: illegal option for ALTER SYSTEM.
Is there anything wrong in the code front if not what could be the workaround for this
If LISTAGG won't work (as, obviously, resulting string is longer than 4000 characters), switch to not-that-elegant XMLAGG which doesn't have that restriction. Result should be the same (compare these two):
SQL> select listagg(dname, ',') within group (order by dname) result
2 from dept;
RESULT
--------------------------------------------------------------------------------
ACCOUNTING,OPERATIONS,RESEARCH,SALES
SQL> select rtrim(xmlagg(xmlelement(e, dname ||',') order by dname).extract
2 ('//text()'), ',') result
3 from dept;
RESULT
--------------------------------------------------------------------------------
ACCOUNTING,OPERATIONS,RESEARCH,SALES
SQL>

Select values from a table if the table name has timestamp in postgreSQL from R

I connected from R to the PostgreSQL and i am able to write a table by using timestamp as table name, But i am unable to extract the values.
I used the following code.
library(DBI)
con <- dbConnect(RPostgres::Postgres(),dbname = 'postgres',
host = 'hostname',
port = 5432,
user = 'username',
password = 'pwd')
tm<-paste0('job_status_',Sys.time())
dbWriteTable(con,tm,jbs)
dbGetQuery(con,paste0('select * from ',tm))
When I ran the select command, I got the following syntax error.
Error in result_create(conn#ptr, statement) :
Failed to prepare query: ERROR: syntax error at or near "-"
LINE 1: select * from job_status_2019-03-12 04:33:08
Can anyone help me to resolve this issue?!
As your table name contains characters - :, it needs to be quoted with " to be understood as a table name.
dbGetQuery(con,paste0('select * from "',tm, '"'))
BTW. It may be a good idea to avoid unusual characters in tables' names and limit yourself to just letters, digits and underscore (_). To achieve that you can utilize gsub().
tm<-gsub('-|:| ', '_', paste0('job_status_',Sys.time()))
dbWriteTable(con,tm,jbs)
dbGetQuery(con,paste0('select * from ',tm))

Convert NULL to Blank TPT Fast Load

Insert into emp values
(:FNAME ,.......
Above Sample Code from TPT works fine.
I want to convert null values in flatfile to blank while loading
insert into emp values ( COALESCE(:Fname,' '),.... -- Throws ERROR
TPT_INFRA: TPT04046: Error: Line 193 of Job Script File 'tpscript4.txt': Adjacen
t quoted strings must be separated by the
concatenation operator: '||'.
Job script preprocessing failed.
insert into emp Values ( case when :Fname is null then ' ' else :Fname End,... --Throws Error
Teradata Parallel Transporter Version 13.10.00.02
TPT_INFRA: TPT04046: Error: Line 191 of Job Script File 'tpscript4.txt': Adjacen
t quoted strings must be separated by the
concatenation operator: '||'.
Job script preprocessing failed.
Job terminated with status 8.
When used Case when in Select oerator for fastload:
TO OPERATOR (UPDATE_OPERATOR[2])
SELECT case when FNAME is null then ' ' else FNAME,LNAME,....
FROM OPERATOR (FILE_READER[2]);
ERROR:
TPT_INFRA: Syntax error at or near line 249 of Job Script File 'tpscript4.txt':
TPT_INFRA: At "SELECT" missing SEMICOL_ in Rule: Job Definition Body
Compilation failed due to errors. Execution Plan was not generated.
Job script compilation failed.
Job terminated with status 8.
Note: with out the case in select it is working fine ,
APPLY('insert into emp values ( COALESCE(:Fname,'' ''),....') Worked with Mload
and
SELECT CASE WHEN Fname IS NULL THEN ' ' ELSE Fname END AS Fname,... FROM OPERATOR worked with Fload
You didn't specify which error is returned, i assume it's related to the single quotes. Your INSERT is probably within an APPLY('INSERT ....;') you might try two single quotes to get one quote in a string:
APPLY('insert into emp values ( COALESCE(:Fname,'' ''),....')
Or do it in the SELECT (COALESCE is not supported here):
SELECT
CASE WHEN Fname IS NULL THEN ' ' ELSE Fname END AS Fname,
...
FROM OPERATOR

How to get trailing spaces from varchar column in Informix using ODBC

I cannot get trailing spaces from varchar column in Informix database.
I created test table, filled it with field with some trailing spaces,
but they are not returned by SELECT while it seems they are stored in db.
CREATE TABLE tmptable (txt varchar(240));
INSERT INTO tmptable (txt) VALUES ('123 ');
SELECT txt, txt || '***', LENGTH(txt) FROM tmptable;
And I got fields:
1: '123' : no trailing spaces!!!
2: '123 ***' : it seems that spaces are stored!!!
3: 3 : LENGTH() do not count trailing spaces!!!
Other databases I tested: Oracle and PostgreSQL return varchar fields
with trailing spaces. I tried RPAD() but with no success. Is there any way to get
trailing spaces?
Server: IBM Informix Dynamic Server Version 11.50.TC2DE
Client: tested with both ISA (no spaces in HTML page source) and ODBC driver 3.50.TC3DE
EDIT
Simple Python test program (tested with ActivePytnon 2.6 on Windows, you must change connection string in the last lines)
import odbc
def test_varchar(db_alias, dbname):
print
print
arr = db_alias.split('/')
print '%s %s' % (arr[0], dbname)
print '--------------'
connection = odbc.odbc(db_alias)
try:
cursor = connection.cursor()
cursor.execute("DELETE FROM tmptable;")
cursor.execute("INSERT INTO tmptable (txt) VALUES (' %s ')" % (dbname))
#cursor.commit()
cursor.execute("SELECT txt, txt || '***', LENGTH(txt) FROM tmptable;")
for row in cursor.fetchall():
print '[%s]\t[%s]\t[%s]' % (row[0], row[1], row[2])
finally:
connection.close()
#test_varchar('database/user/passwd', 'DBproducer')
test_varchar('oracledb/usr/passwd', 'Oracle ')
test_varchar('informixdb/usr/passwd', 'Informix ')
test_varchar('postgresqldb/usr/passwd', 'PostgreSQL')
And results:
c:\tools\pyscripts\scripts\db_examples>test_odbc.py
oracledb Oracle
--------------
[ Oracle ] [ Oracle ***] [16]
informixdb Informix
--------------
[ Informix] [ Informix ***] [11]
postgresqldb PostgreSQL
--------------
[ PostgreSQL ] [ PostgreSQL ***] [16]
Similar program in Jython using JDBC:
works (do not trim trailing spaces)
with native JDBC driver
doesn't work
(trim trailing spacec) with JDBC-ODBC
bridge
Source:
# for Jython 2.5 invoke with --verify
# beacuse of bug: http://bugs.jython.org/issue1127
import sys
from com.ziclix.python.sql import zxJDBC
def test_varchar(driver, db_url, usr, passwd):
arr = db_url.split(':', 2)
dbname = arr[1]
if dbname == 'odbc':
dbname = db_url
print "\n\n%s\n--------------" % (dbname)
try:
connection = zxJDBC.connect(db_url, usr, passwd, driver)
except:
ex = sys.exc_info()
s = 'Exception: %s: %s\n%s' % (ex[0], ex[1], db_url)
print s
return
cursor = connection.cursor()
cursor.execute("SELECT txt, txt || '***', LENGTH(txt) FROM tmptable")
for row in cursor.fetchall():
print '[%s]\t[%s]\t[%s]' % (row[0], row[1], row[2])
#test_varchar(driver, db_url, usr, passwd)
test_varchar("org.postgresql.Driver", 'jdbc:postgresql://127.0.0.1/pg_testdb', 'postgres', 'postgres')
test_varchar("oracle.jdbc.driver.OracleDriver", 'jdbc:oracle:oci:#MNTEST', 'user', 'passwd')
test_varchar("com.informix.jdbc.IfxDriver", 'jdbc:informix-sqli://127:0:0:1:9088/test_td:informixserver=ol_mn;DB_LOCALE=pl_PL.CP1250;CLIENT_LOCALE=pl_PL.CP1250;charSet=CP1250', 'user', 'passwd')
# db_url = jdbc:odbc:[ODBC source name]
test_varchar("sun.jdbc.odbc.JdbcOdbcDriver", 'jdbc:odbc:inf_test_db_odbc', 'user', 'passwd')
test_varchar("sun.jdbc.odbc.JdbcOdbcDriver", 'jdbc:odbc:ora_testdb_odbc', 'user', 'passwd')
test_varchar("sun.jdbc.odbc.JdbcOdbcDriver", 'jdbc:odbc:pg_testdb_odbc', 'postgres', 'postgres')
Results (for Informix only):
C:\tools\pyscripts\scripts\db_examples>jython --verify test_jdbc2.py
informix-sqli
--------------
[ Informix ] [ Informix ***] [11]
jdbc:odbc:inf_test_db_odbc
--------------
[ Informix] [ Informix ***] [11]
In ESQL/C, it is most certainly possible to get the trailing spaces from a VARCHAR column; my SQLCMD program (available from the IIUG Software Archive) does it. But you have to be extremely careful to use the correct type for the variables that hold the result. By default, the various char types are treated as CHAR rather than VARCHAR, and the libraries strip trailing blanks from CHAR values unless you direct otherwise (and blank pad to full length when you do direct otherwise).
Regarding ISA: I don't know how you established what it returns. I'm not altogether surprised that it loses the trailing blanks. Similar comments would apply to DB-Access.
Regarding ODBC: can you show the code, please, because although it is possible that there's a bug in the code (thank you for including the version information - it helps, and reassures me you are effectively up-to-date with your system), it is more likely that there is something up with the code you wrote to use it.
Regarding LENGTH(): it is defined to remove trailing blanks before calculating the length; it always treats its argument as if it was a CHAR value rather than as a VARCHAR value.
Taking your code and using SQLCMD:
Black JL: sqlcmd -d stores - <<!
> CREATE TABLE tmptable (txt varchar(240));
> INSERT INTO tmptable (txt) VALUES ('123 ');
> SELECT txt, txt || '***', LENGTH(txt) FROM tmptable;
> !
123 |123 ***|3
Black JL:
'Black JL:' is my Unix prompt on machine 'black'; as you can see, I got the trailing blanks OK (but I wrote SQLCMD about 20 years ago, now, in part because DB-Access, or rather its predecessor ISQL, didn't do things carefully enough for my purposes).
For anyone that doesn't feel like guessing what the "correct type" is, I've gotten my esql program to work by specifying a "lvarchar" type. (at least one version of the esql/c guide implies that "varchar" should work, but it didn't for me)

Resources