MySQL function to quote identifiers with backticks - mysql

Is there a MySQL built-in function that surrounds indentifiers (simple or qualified) with backticks? I.e. such function f would work like:
f('my') would return `my`,
f('my.table') would return `my`.`table`, and
f(`my`) would return `my`

Usually this is a function of your database driver and not your database. The backticks are used by the MySQL statement parser to properly tokenize your statement, so a function that returns values like that would be meaningless since those would be strings and not table or column tokens.
Your database driver may have a function for escaping table names, and if so, use that. Otherwise you'll need to roll your own somehow.

concat('`',replace(your_identifier,'`','``'),'`')

Related

How can I trim Schema/Database Name in MySQL

An Application I am using is passing schema name as a string literal and it is getting single quoted and generating MySQL Syntax error:
'somedatabasename'
I want to trim the single quotes and use the schema name to form my query.
SELECT field FROM somedatabasename.sometable
I can only use a single Query and cannot use Stored Procedure (I know using stored functions I can manipulate the strings.)
Is there a way in MySQL where I can Use TRIM or REPLACE with the FROM keyword.

Script does not work when place the function inside the WHERE clause

I am trying to create a stored procedure, which receives a string and places it in the WHERE clause after processing it.
I created the function and when I call it from the body of a SQL statement, it returns the correct values:
('J1245',j3456','j1098')
However, when I call the function inside the WHERE clause as shown below, SQL does not show any records.
(Altcode in dbo.myfunction(#codes))
When I hard code it inside the WHERE clause, the SQL statement shows records.
(Altcode IN ('J1245',j3456','j1098'))
I suspect the function is returning a string (VARCHAR). If we reference the function anywhere in a SQL statement, the value returned by the function serves as a scalar value. The contents of the value don't change that. Any punctuation, single quotes, backticks, parens, commas, keywords, identifiers, et al. that happen to appear in the string are just part of the value.
The parser sees the return from the function simply as a single value, not as part of the SQL text.
It's not possible (in a single statement) to make the value returned by a function "become" part of the SQL text to be parsed.
As an example, in the WHERE clause, if we write:
WHERE altcode IN ( myfunc() )
The function myfunc is going to be evaluated, and the return will be single value, of a certain datatype, for example maybe a VARCHAR. Any parens or commas within the value are not interpreted as part of the SQL text. Those are just characters that are within the value.
It's as if we wrote SQL like this:
WHERE altcode IN ( ? )
And supplied a single value in place of the question mark placeholder. The SQL parser isn't seeing a list of values, it's not seeing any SQL to be executed. All the statement is seeing is a value.
It matters not one whit that we might supply a value that looks like SQL text, for example:
WHERE altcode IN ( '(SELECT code FROM all_altcodes)' )
That would be equivalent to writing
WHERE altcode = '(SELECT code FROM all_altcodes)'
And that is going to look for an exact match of altcode to the string literal.
Seems like there's a single quote missing in the value returned by the function, but maybe that's a typo in the question.
To get the string value returned by the function included as part of the SQL text, we would need to use dynamic SQL.
We would have to first call the function, and return the string. And then do some string concatenation to come up with another string that contains the SQL statement we want to execute, and then execute that string as a SQL statement.
So that would be two separate statement executions... one to get the function evaluated; and a second statement that is dynamically constructed, as a string, incorporating the value returned by the function.
(The question is tagged "MySQL", but I suspect this question is actually regarding SQL Server (given the reference to dbo. ?)
Preparing and executing dynamic SQL is similar in MySQL and SQL Server, but there are differences in the syntax.

How to escape a whole sql string instead of escaping each argument?

I use https://github.com/mysqljs/mysql.git library.
I have a mysql db query architecture in which I can not modify the SQL query file one by one to escape each argument for there are too many files, but all the SQL queries will call the query method of a same base mysql instance, so I wonder if I can escape the eventual SQL string in the base mysql query method.
I want to escape the whole SQL string like
select * from tableA where name = 'foo'bar
to
select * from tableA where name = 'foo\'bar'
with some function like mysql_escape("select * from tableA where name = 'foo'bar'") instead of doing this using preparing queries or concating escaped strings.
There isn't a way to do this that wont result in a really inefficient function or some bad hack. Just use parameterized queries, Its basically what they are there for. If you cant use those you use concat strings.
Running mysql_escape on a whole query will require the function to know what characters are part of your query and what characters are part of the input values. You could write some kind of stupid regex to try pull the values from the query and then escape them but its just a bad idea.

Easy way of changing the delimiter in postgreSQL

I want to know how to do this, because after looking around, all I found are long and complicated ways to do this seemingly easy job.
In MySQL, we had
DELIMITER //
...function start
INSERT INTO table VALUES (1);
...function end//
DELIMITER ;
which was really useful when we wanted to use stored procedures or funtions. I'm looking for the equivalent of this in postgreSQL, if there is one.
Thanks in advance!
The issue with the MySQL DELIMITER plays out quite differently in PostgreSQL. (First of all, most programmers would not use the psql command line to enter a function; instead you'd write a SQL script file and execute that, but this is besides the point of your question.)
In PostgreSQL the function body is basically a long string. That string can be delimited by basically anything that does not conflict with anything else. In the SQL standard - and also in the PostgreSQL documentation - single quotes ' are used, instead of just starting the function body unquoted like in MySQL. So when you write a function header (CREATE FUNCTION ...) you would write a quote to start the function body before you write any semi-colon to terminate statements inside the function. That means that the MySQL problem with the semi-colon does not exist in PostgreSQL: the parser is just reading a string and waiting for that string to be completed with a closing quote and then the command terminated with a semi-colon.
There is more to it, however.
In PostgreSQL the convention is to use $$ or $anything_goes_here$, the so-called dollar quoting, instead of a ' to start the function body. The reason for this is that it avoids having to escape embedded quotes in the function body. See the docs for an explanation of this feature.
The generic function definition looks somewhat like this:
CREATE FUNCTION my_func(arg1 data_type, ...) RETURNS data_type AS $body$
INSERT INTO foo(my_column) VALUES(arg1)
RETURNING some_column;
$body$ LANGUAGE sql;
Note that there are also other programming languages in PostgreSQL - most notably PL/pgSQL, the built-in procedural languages, but also variants of Perl, Python, Tcl, C, ... - and all use the same function definition syntax (as per the SQL standard) including the delimiters, only the function body will differ.
You can use different delimiters for different functions too, but the opening and closing delimiters of a single function need to match.

DECODE Function in SQL

I am trying to insert the following query and I get syntax errors. Can you please help me with the below query:
INSERT INTO ABCTABLE (COLUMN1) values ('DECODE(MDSE_CD,NULL,'0000000000000000',LPAD(TO_NUMBER(MDSE_CD,'16',' '))');
Since you haven't really said anything other than "this query doesn't work, fix it", I have to take a stab in the dark what you want. From the query you have, I'm therefore guessing you want the value of the column to be DECODE(MDSE_CD,NULL,'0000000000000000',LPAD(TO_NUMBER(MDSE_CD,'16',' '))
In which case, you have to escape the single quotes within your string literal. Do this by doubling up the quotes:
INSERT INTO ABCTABLE (COLUMN1)
VALUES ('DECODE(MDSE_CD,NULL,''0000000000000000'',LPAD(TO_NUMBER(MDSE_CD,''16'','' ''))')
Try properly escaping the inner single quotes
INSERT INTO ABCTABLE (COLUMN1)
VALUES ('**DECODE**(MDSE_CD,NULL,''0000000000000000'',**LPAD**(TO_NUMBER(MDSE_CD,''16'','' ''))');
The problem is the use of quote marks. If we tried to break up your query it would look like this:
INSERT INTO ABCTABLE
(COLUMN1)
values
(
'DECODE(MDSE_CD,NULL,'
0000000000000000
',LPAD(TO_NUMBER(MDSE_CD,'
16
','
'))'
);
...which clearly makes no sense.
You might want to think about how to escape a quote mark inside a string.
Sql Server:
DECOD function in Sql Server can be replaced with CASE construct
LPAD function in Sql Server has not a direct correspondence but you can pad your string using string manage function REPLACE (replicate a character a number of specified times)
My Sql:
DECOD function in MySql can be replaced with CASE construct
LPAD function in MySql is existent
What do you want to store... a string literal 'DECODE(MDSE...))', or did you want to call a function to derive a value?
To store a string literal containing single quotes, you need to "escape" each single quote within the string with an extra single quote, e.g.
O'Hare Int'l ==> 'O''Hare Int''l'
The DECODE function is Oracle specific. That expression will need to be rewritten using different functions in both MySQL and SQL Server.