mysql) select values if table exists - mysql

I'm trying select all values if such table exists. If it doesn't exist, just leave it.
I'm trying to do this only in one MYSQL code. Not with the help of python or something.
SELECT CASE WHEN (SELECT count(*)
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = '{db0}' AND TABLE_NAME = '{table0}')=0
THEN 'None' ELSE (SELECT MAX({colname}) FROM {db0}.{table0}) END;
If i inject existing table name on it, it works well.
But if not , it shows the error sign that saying such table doesn't exist.(Table 'corps.060311' doesn't exist)
What should I do?

This cannot be achieved using a simple query because MySQL analyses the query as a whole before performing it: it is not a procedural language and the queries are never executed line by line.
To do what you want to do without help of any other language, you must use stored procedures: https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html
So the first step is to add a new FUNCTION in your database that will contain the "if table exists" part (see https://dev.mysql.com/doc/refman/8.0/en/if.html for if statements) and will return the desired value based on the schema, table, and column provided as strings in input of the function.
Then you can use the FUNCTION in any query in your database.

Related

What exactly does SELECT database(); mean?

So I'm really new to learning SQL and I'm interested about the command
SELECT DATABASE();
At my point in learning, I know that command is used to show what database I'm currently working with. I accidentally made the typo,
SELECT DATABASE() L; and the MySQL terminal displayed the letter L above the name of the database I was working with. Why does this happen? And what exactly does SELECT DATABASE() mean?
I tried this again and did the command
SELECT DATABASE() HI; and it did the same thing and showed "HI" above the name of my selected database. Using the correct syntax, it normally shows, "DATABASE()" above the db that I'm currently working with.
database() is an information function provided by MySQL to return the name of the current database. It can be used anywhere a string constant would be expected.
MySQL does not require a from clause, so a select is a complete query that returns one row -- the values calculated in the select.
Databases allow you to assign a name ("column alias") to an expression in the select. Normally, this would be written as:
select database() as database_name
However, the as is optional (although I strongly recommend using it for column aliases). And nothing enforces a reasonable name.
So:
select database() l
returns a result set with one row and one column. The column is called l and the value in the one row is the database name.
You are selecting a dataset with one column. The contents of the column is the current database. You are naming that column L.
Compare with
select 4 label;
I am not expert in database. But I am quite sure that show database(); will show you the selected database in other words the database which you have chosen.

Using a pre made sql query to get table structure

I'm rather new at database management, so this might not be feasible, but I got a handful of SQL select queries, rather long ones at that. What I'd like is to get the table column names and structure, without access to the actual database, so as to get a map of all this queries.
context: All we have are the queries used to output tables that will be given to us latter.
This need not be done with actual SQL code, maybe a short script in other language or a utility somebody knows of (but I do have MySQL workbench)
You can add a CREATE TABLE statement in front of your select queries to get the column names.
You cannot infer data types or keys from select queries.
For column names do something like:
drop table if exists your_table_name;
create table your_table_name
select *
from ...
where the select * portion is replaced by the select queries you have.
Then to see the column names in a friendlier way you can do:
show create table your_table_name;
or
desc your_table_name;

Can I check if a table exists before join?

I have the following problem. I have Table A and would like to join to table B if table B exists. Can this be done? I am only writing SQL in WorkBench to try achieve it.
I am aware I cannot use the EXISTS option as I have tried typing it out but it prompts for an error.
Any suggestions would be greatly appreciated.
Thanks.
I managed to do this using EXECUTE, so using a query that is only prepared at runtime:
SET #sqlCommand = IF(
EXISTS (SELECT column_name FROM information_schema.columns WHERE table_schema = '{{yourschemaname}}' AND table_name = '{{yourtablename}}' AND column_name = '{{yourcolumnname}}'),
'SELECT \'Yes! Good to go!\' as ColumnExists',
'SELECT \'Nope!\' as ColumnExists');
PREPARE executable FROM #sqlCommand;
EXECUTE executable;
Note that the two selects at the center (Yes!/No!) are the custom statements that are to be executed conditionally. So if the column exists, the first command is executed (select 'yes!'), otherwise the second one (select 'nope').
I got the hint from this discussion here.. have a look if you're looking for the MSSQL equivalent: https://ask.sqlservercentral.com/questions/97579/check-if-table-exists-in-join.html
Data manipulation language statements are typically written for a specific schema; you are assumed to know what the schema looks like when you issue the statement. So you don't generally have the capacity to ask whether a particular schema object exists or has a particular structure. You could however write a stored procedure that did different things depending upon the schema. You have the ability in a stored procedure to use conditional statements and to look in INFORMATION_SCHEMA.

MySQL - Automate a view update

I'd like to know if it is possible to create an SQL function that will automatically update my View and add to it new tables in my DB.
My DB consist of multiple tables (same data structure) and are named as follow "MM_DD", now I would like to create a VIEW that joins all this data ( pretty simple , see query below) but I wish to automate the process so every time a new table is added the view will update.
CREATE OR REPLACE VIEW `viewTable` AS
select *,
md5(CONCAT(`columnA`,`columnB`)) AS myPK_id
from `05_06`
union all
select *,
md5(CONCAT(`columnA`,`columnB`)) AS myPK_id
from `05_08`
ect...
What I am doing at the moment is using PHP every time a table is added. It loops through the tables and create / update the view.
select * from information_schema.tables WHERE table_name LIKE '%05%'
Now that I have an array of table names -> create my Query string -> replace view...
Is this possible to do this in SQL?
If so, what is the correct approach?
Write a stored procedure to rebuild your view. You'll need to use what MySQL internally calls "prepared statements" so you can use string manipulation.
You'll still use your SELECT ... FROM information_schema.tables query to drive this stored procedure.
Once you get this working, you can embed it in a mySQL event, and arrange to run it automatically. For example, you could run it at the same time late at night.
Or, you can invoke the stored procedure immediately after you create one of these tables.

MySQL to SQL Server select statement

I am converting mysql sprocs to SQL Server. I've come across a select statement in mysql that I don't quite understand what it's doing and my google-fu/so-fu has failed me. Here is the gist of it:
SELECT AccountType = dbo.functionToGetAccountType() FROM AccountLookup
I don't have the ability to debug the original mysql. I do know that the function only returns a single value.
Is the mysql statement assigning a default value to 'AccountType' in the event there are no rows in the AccountLookup table?
Thanks for your time.
The select statement is executing the function dbo.functionToGetAccountType() and aliasing the column as AccountType. It could be re-written as:
SELECT dbo.functionToGetAccountType() as AccountType
FROM AccountLookup