Mariadb - Diffferences between executing a file vs pasting same code into console - console

I’m trying to make the move from SQL Server to Mariadb and I’m running into a lot of little quirks that drive me crazy at times. Chief among them are the apparent differences between executing a script from a file and pasting it into a console window. I was used to using tabs for formatting code in MSSQL, so I’m still trying to get used to the tab behavior in the Mariadb console, but at least that makes sense. The difference between var and #var is odd to me as well. The code below runs fine when execute through Pycharm, but fails when pasted into a console window. I’m running Mariadb (##version: 10.5.18-MariaDB-0+deb11u1) on a Pi Raspberry accessing it through SSH from a Windows 11 box.
All the script is doing is populating a table with random combinations of last names and male/female first names from U.S. census data for testing. Any help with the error would be greatly appreciated. I really want to understand why the difference between pasting and executing the file.
SET #loops := 10;
WHILE #loops > 0 DO
INSERT person(last_name, first_name, iso_country)
VALUES(census.random_name(0), census.random_name(FLOOR(1 + RAND() * (2 - 1 +1))), 'US');
SET #loops := #loops - 1;
END WHILE;
SELECT * FROM person;
ERROR 1064 (42000): 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 'END WHILE' at line 1
I executed the file from the Pycharm IDE where it runs fine, and pasted the same code into the Mariadb console where the error was raised, and the insertions did not occur.

The mariadb command line client has it's own small parser, by default a semicolon is interpreted as end of statement.
With default delimiter ; your statement is splitted after first semicolon into WHILE #loops > 0 DO INSERT person(last_name, first_name, iso_country) VALUES(census.random_name(0), census.random_name(FLOOR(1 + RAND() * (2 - 1 +1))), 'US'); SET #loops := #loops - 1; and END WHILE. When sending both statements to the server, server will return 2 errors, but only last error is displayed.
Instead you should use a different delimiter:
DELIMITER $$
WHILE #loops > 0 DO
INSERT person(last_name, first_name, iso_country)
VALUES(census.random_name(0), census.random_name(FLOOR(1 + RAND() * (2 - 1 +1))), 'US');
SET #loops := #loops - 1;
END WHILE;$$
See also Delimiters

Related

Golang exec.Command Output blank(no error)

I am attempting to run a sqlite3 command from within Go, to do a simple query (I completly understand there are other ways to access sqlite from go, but thats not the issue here)
func sqliteTest(){
cmd:=exec.Command("/usr/bin/sqlite3", " /home/chadg/Downloads/testDb.db 'select * from testTable;'")
fmt.Println("Command String:",cmd.String())
out,err:=cmd.CombinedOutput()
if err!=nil{
fmt.Println("Error Accessing Database:",err.Error(),string(out))
return
}
fmt.Println("Result Length:",len(out))
fmt.Println("Result:",string(out))
}
Running this gives me this output:
Command String: /usr/bin/sqlite3 /home/chadg/Downloads/testDb.db 'select * from testTable;'
Result Length: 0
Result:
Process finished with exit code 0
However if I run the same command by hand:
$ /usr/bin/sqlite3 /home/chadg/Downloads/testDb.db 'select * from testTable;'
testName|testValue
Have certainly run into many issues when running commands from within go, but there is always an error generated, but this time, there is no error, but the result from stdout and stderr seems to both be empty.
EDIT:
Single quotes vs double quotes doesn't change anything
cmd:=exec.Command("/usr/bin/sqlite3", " /home/chadg/Downloads/testDb.db \"select * from testTable;\"")
still returns an empty output, but works as expected from the command line.
Arguments in exec.Command should be passed as separate strings.
cmd := exec.Command("/usr/bin/sqlite3", "/home/chadg/Downloads/testDb.db", "select * from testTable;")
As for the behavior you're observing:
When sqlite3 is started non-interactively with 1 argument, it treats that as the database file name and reads the query from stdin, but cmd.CombinedOutput() closes stdin, resulting in an empty output.

random value is getting replaced in oracle procedure after compilation

I am running a code in a plsql package where I am using bind variable like this -
sql:= 'insert into test_table select * from '||dynamic_table||' where id = :bind1 and nvl(col1,:X)=:X';
execute immediate sql using vid,'Y','Y';
code is all compiled and running but whenever I am compiling and checking the body of my package the execute immediate get automaticlly replaced by some random letter 'u' like below-
execute immediate sql using vid,'u','Y';
Why is this happening, there is no compilation issue but correct value is not getting inserted because of this random letter u.

Create a stored procedure using RMySQL

Background: I am developing a rscript that pulls data from a mysql database, performs a logistic regression and then inserts the predictions back into the database. I want the entire system to be self contained in the script in case of database failure. This includes all mysql stored procedures that the script depends on to aggregate the data on the backend since these would be deleted in such a database failure.
Question: I'm having trouble creating a stored procedure from an R script. I am running the following:
mySQLDriver <- dbDriver("MySQL")
connect <- dbConnect(mySQLDriver, group = connection)
query <-
"
DROP PROCEDURE IF EXISTS Test.Tester;
DELIMITER //
CREATE PROCEDURE Test.Tester()
BEGIN
/***DO DATA AGGREGATION***/
END //
DELIMITER ;
"
sendQuery <- dbSendQuery(connect, query)
dbClearResult(dbListResults(connect)[[1]])
dbDisconnect(connect)
I however get the following error that seems to involve the DELIMITER change.
Error in .local(conn, statement, ...) :
could not run statement: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER //
CREATE PROCEDURE Test.Tester()
BEGIN
/***DO DATA AGGREGATION***/
EN' at line 2
What I've Done: I have spent quite a bit of time searching for the answer, but have come up with nothing. What am I missing?
Just wanted to follow up on this string of comments. Thank you for your thoughts on this issue. I have a couple Python scripts that need to have this functionality and I began researching the same topic for Python. I found this question that indicates the answer. The question states:
"The DELIMITER command is a MySQL shell client builtin, and it's recognized only by that program (and MySQL Query Browser). It's not necessary to use DELIMITER if you execute SQL statements directly through an API.
The purpose of DELIMITER is to help you avoid ambiguity about the termination of the CREATE FUNCTION statement, when the statement itself can contain semicolon characters. This is important in the shell client, where by default a semicolon terminates an SQL statement. You need to set the statement terminator to some other character in order to submit the body of a function (or trigger or procedure)."
Hence the following code will run in R:
mySQLDriver <- dbDriver("MySQL")
connect <- dbConnect(mySQLDriver, group = connection)
query <-
"
CREATE PROCEDURE Test.Tester()
BEGIN
/***DO DATA AGGREGATION***/
END
"
sendQuery <- dbSendQuery(connect, query)
dbClearResult(dbListResults(connect)[[1]])
dbDisconnect(connect)

teradata export query using cmd windows not working

new post :
i already read tutorial and i found this script
.LOGMECH LDAP;
.LOGON xx.xx.xx.xx/username,password;
.LOGTABLE dbname.LOG_tablename;
DATABASE dbname;
.BEGIN EXPORT SESSIONS 2;
.EXPORT OUTFILE D:\test.txt
MODE RECORD format text;
select a.my_date,b.name2,a.value from dbsource.tablesource a
inner join dbname.ANG_tablename b
on a.name1=b.name2
where value=59000
and a.my_date >= 01/12/2015
;
.END EXPORT;
.LOGOFF;
but it is like not working
D:\>bteq < dodol.txt
BTEQ 15.00.00.00 Tue Jan 05 14:40:52 2016 PID: 4452
+---------+---------+---------+---------+---------+---------+---------+----
.LOGMECH LDAP;
+---------+---------+---------+---------+---------+---------+---------+----
.LOGON xx.xx.xx.xx/username,
*** Logon successfully completed.
*** Teradata Database Release is 13.10.07.12
*** Teradata Database Version is 13.10.07.12
*** Transaction Semantics are BTET.
*** Session Character Set Name is 'ASCII'.
*** Total elapsed time was 4 seconds.
+---------+---------+---------+---------+---------+---------+---------+----
.LOGTABLE dbname.LOG_tablename;
*** Error: Unrecognized command 'LOGTABLE'.
+---------+---------+---------+---------+---------+---------+---------+----
DATABASE dbname;
*** New default database accepted.
*** Total elapsed time was 2 seconds.
+---------+---------+---------+---------+---------+---------+---------+----
.BEGIN EXPORT SESSIONS 2;
*** Error: Unrecognized command 'BEGIN'.
+---------+---------+---------+---------+---------+---------+---------+----
.EXPORT OUTFILE D:\test.txt
*** Warning: No data format given. Assuming REPORT carries over.
*** Error: Expected FILE or DDNAME keyword, not 'OUTFILE'.
+---------+---------+---------+---------+---------+---------+---------+----
MODE RECORD format text;
MODE RECORD format text;
$
*** Failure 3706 Syntax error: expected something between the beginning of
the request and the 'MODE' keyword.
Statement# 2, Info =6
*** Total elapsed time was 1 second.
+---------+---------+---------+---------+---------+---------+---------+----
select a.my_date,b.name2,a.value from dbsource.tablesource a
inner join dbname.ANG_tablename b
on a.name1=b.name2
where value=59000
and a.my_date >= 01/12/2015
;
old post :
I am new in teradata, i have found mload to upload big data, now i have question, is there option to use cmd ( win7 ) to export data from teradata to xxx.txt
--- sample
select a.data1,b.data2,a.data3 from room1.REPORT_DAILY a
inner join room1.andaikan_saja b
on a.likeme=b.data2
where revenue=30000
and content_id like '%super%'
and a.trx_date >= 01/12/2015
;
this is my mload up.txt
.LOGMECH LDAP;
.LOGON xx.xx.xx.xx/username,mypassword;
.LOGTABLE mydatabase.LOG_my_table;
SET QUERY_BAND = 'ApplicationName=TD-Subscriber-RechargeLoad; Version=01.00.00.00;' FOR SESSION;
.BEGIN IMPORT MLOAD
TABLES mydatabase.my_table
WORKTABLES mydatabase.WT_my_table
ERRORTABLES mydatabase.ET_my_table mydatabase.UV_my_table;
.LAYOUT LAYOUT_DATA INDICATORS;
.FIELD number * VARCHAR(20);
.DML LABEL DML_INSERT;
INSERT INTO mydatabase.my_table
(
number =:number
);
.IMPORT INFILE "D:\folderdata\data.txt"
LAYOUT LAYOUT_DATA
FORMAT VARTEXT
APPLY DML_INSERT;
.END MLOAD;
.LOGOFF &SYSRC;
i need solution to export file to my laptop, just like my script that i put ---sample title ....
i use that script from teradasql, and i am search for cmd script
If it's just a few MB and an adhoc export you can use SQL Assistant: Set the delimiter in Tools-Options-Export/Import, maybe modify the settings in Tools-Options-Export and then click File-Export Results before submitting your Select. (Similar in TD Studio)
Otherwise the easiest way to extract data in a readable delimited format is TPT, either Export for large amounts of data (GBs) or SQL Selector (MBs). TPT is available for most Operating Systems including Windows.
There's a nice User Guide with lots of example scripts:
Job Example 12: Extracting Rows and Sending Them in Delimited Format
In your case you'll define a generic template file like this:
DEFINE JOB EXPORT_DELIMITED_FILE
DESCRIPTION 'Export rows from a Teradata table to a delimited file'
(
APPLY TO OPERATOR ($FILE_WRITER() ATTR (Format = 'DELIMITED'))
SELECT * FROM OPERATOR ($SELECTOR ATTR (SelectStmt = #ExportSelectStmt));
);
Change $SELECTOR to $EXPORT for larger exports.
Then you just need a job variable file like this:
SourceTdpId = 'your system'
,SourceUserName = 'your user'
,SourceUserPassword = 'your password'
,FileWriterFileName = 'xxx.txt'
,ExportSelectStmt = 'select a.data1,b.data2,a.data3 from room1.REPORT_DAILY a
inner join room1.andaikan_saja b
on a.likeme=b.data2
where revenue=30000
and content_id like ''%super%''
and a.trx_date >= DATE ''2015-12-01'' -- modified this to a valid date literal
;'
The only bad part is that you have to double any single quotes within your select, e.g. '%super%' -> ''%super%''.
Finally you run a cmd:
tbuild -f your_template_file -v your_job_var_file
Depending on the volume of data you wish to extract from Teradata you can use Teradata BTEQ or the Teradata Parallel Transport (TPT) utility with the EXPORT operator from the command line to extract the data.
The TPT utility is the eventual replacement for the legacy Teradata Load and Unload utilities (FastLoad, MultiLoad, FastExport, and TPump) and provides an easier mechanism to produce delimited flat files over FastExport. TPT is fairly flexible and effective for exporting large volumes of data to channel or network attached clients.
Teradata BTEQ can perform lightweight load and unload functions. The BTEQ manual is pretty good at providing you an overview of how to use the various commands to produce a semi-structured report or data extract. It doesn't have a simple command to produce a delimited flat file. If you review the manual's overview of the EXPORT command you should get a good feel for how BTEQ behaves when working with channel or network attached clients.

Accessing Bind Variable in PL/SQL

I am trying to run a program in the Oracle express edition editor. When I execute the program, I get an error
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
Can anyone help me understand why I am getting an error and how to fix the code?
VARIABLE gvn_total_salary NUMBER;
DECLARE
vn_base_salary NUMBER := 3000;
vn_bonus NUMBER := 1000;
BEGIN
:gvn_total_salary := vn_base_salary + vn_bonus;
END;
The output I'm getting
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
Run By SYSTEM
Parsing Schema SYSTEM
Script Started Thursday, April 26, 2012
3 seconds ago
Elapsed time 0.01 seconds
Statements Processed 1
Successful 0
With Errors 1
With the declaration of the bind variable, that code works fine for me in SQL*Plus
SQL> VARIABLE gvn_total_salary NUMBER;
SQL> DECLARE
2 vn_base_salary NUMBER := 3000;
3 vn_bonus NUMBER := 1000;
4 BEGIN
5 :gvn_total_salary := vn_base_salary + vn_bonus;
6 END;
7 /
PL/SQL procedure successfully completed.
SQL> print gvn_total_salary
GVN_TOTAL_SALARY
----------------
4000
Can you connect to the database using SQL*Plus and run the same thing?
What are you actually trying to accomplish? This script won't execute in sqlplus or Oracle Developer or any PL/SQL execution environment I can think of. In fact, I don't understand how you are passing the bind variable :gvn_total_salary and how you can get the error you are describing. You should get something like "bind variable gvn_total_salary" not declared.

Resources