Pass database name as a parameter in mySQL - mysql

set #sourcedb = 'testdb1' set #destinationdb = 'testdb2' CREATE TABLE IF NOT EXISTS #destinationdb.Testtable Like #sourcedb.Testtable;
I have tried copy one table from one database to another database with same name.
how to pass database name as a parameter?

I've tried that before but id doesn't work. I wonder if there's a way to that way though. In the meantime I'm just using prepared statement instead. See example query below:
SET #ctable='CREATE TABLE testdb12.testtable LIKE testdb21.testtable';
PREPARE stmt FROM #ctable;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Now, I don't really know your usage but in my case, I use this to create a new table on the 1st every month. So I keep this query in a text file, use a batch script to call it and then use task schedule to execute it every 1st of the month (yes, I'm using Windows). Hopefully, this might be what you're looking for.
*I found this solution in one of the answer here but I can't remember/didn't bookmark the solution. I would like to credit this properly.
Edit : I found this mysql create table dynamically .. maybe you can use it

Related

Select Into/Insert Into SQL Server query duplicates

Sorry for asking this question, but I am a beginner in SQL, my colleague at work build a view, which I need as datasource for a report, however since this view is based on several other views it takes like 45 minutes to execute the query. This is way to long. Therefore I created a table from that view, initial execution time is the same, but once in place it executes in seconds.
In Microsoft SQL Server 2014 I used the following query:
select *
into [dbo].[MAT_v_demnew_daily_am_all_data]
from [dbo].[v_demnew_daily_am]
This works fine, but since the view is updated daily I also need to refresh the table everyday. When I now execute the above mentioned query I get the message that the table already exists.
That's why I tried to use 'insert' in this case:
insert into [dbo].[MAT_v_demnew_daily_am_all_data]
select *
from [dbo].[v_demnew_daily_am]
Here I have the problem that it not only inserts the additional data but also the already existing data, so in the end I have duplicates.
As a workaround I now manually delete the [dbo].MAT_v_demnew_daily_am_all_data] table and then execute the select * into query.
Now I am looking for an easier solution, is it possible to having the table deleted by query and in the same query create a new one by select * into or is it possible to only insert new data from the view to the table so that I don't get duplicates.
Moreover, is it possible to have such SQL statement being executed automatically on a daily basis, maybe by .bat file and windows task scheduler?
I know that the source of all problems is the View and that we should improve that, but looking for a short term solution first.
Thanks so much.
Mathias
Try this:
IF OBJECT_ID('dbo.MAT_v_demnew_daily_am_all_data', 'U') IS NOT NULL
DROP TABLE dbo.MAT_v_demnew_daily_am_all_data
SELECT INTO dbo.MAT_v_demnew_daily_am_all_data FROM dbo.v_demnew_daily_am
This query is reusable on a daily basis.
You can create one stored procedure including this query.
Then you only need to execute the stored procedure.
Updated
Before you create the stored procedure, please check if you have the permission.
Then try:
create procedure [procedure_name]
as
IF OBJECT_ID('dbo.MAT_v_demnew_daily_am_all_data', 'U') IS NOT NULL
DROP TABLE dbo.MAT_v_demnew_daily_am_all_data
SELECT INTO dbo.MAT_v_demnew_daily_am_all_data FROM dbo.v_demnew_daily_am;
After you create it:
EXEC [procedure_name];

how to take periodically database script backup using event in mysql

I want to take database script backup every day using event in mySql ..I am new to mySql , so unable to find out exact solution..can anybody help me to do so??
Tried it using mysqldump utility but it is command promt oriented , i want it to be done through event scheduler only.
DELIMITER $$
create EVENT `Backup`
ON SCHEDULE EVERY 1 minute
STARTS '2016-02-25 17:08:06' ON COMPLETION PRESERVE ENABLE
DO
BEGIN
SET #sql_text = CONCAT("SELECT * FROM purpleaid INTO OUTFILE '/C:/Users/Admin123/Desktop/db/" , DATE_FORMAT( NOW(), '%Y%m%d') , "db.csv'" );
PREPARE s1 FROM #sql_text;
EXECUTE s1;
DEALLOCATE PREPARE s1;
END $$
DELIMITER ;
tried this , but its for single table only.I want complete database script
You can use information_schema.tables table to get list of tables within a database, and information_schema.columns table to get list of columns (just in case you want to have column names included in the backup files).
Create a cursor by getting all table names from your database
Loop through the cursor and get the table name into a variable
Construct your select ... into outfile ... statements the same way as you do in your current code, just add the table name from the variable.
Execute the prepared statement.
If you want to add the column names dynamically to the output, then combine Joe's and matt's answers from this SO topic.
UPDATE
For views, stored procedures, functions, and triggers (and tables, for that matter) the issue is that you can't really interact with show create ... statements' results within sql. You can try to recreate their definitions from their respective information_schema tables, but as far as I know, it is not possible to fully reconstruct each object just based on these tables. You need to use an external tool for that, such us mysqldump. If you want a full backup option, then you would be a lot better off, if you used an external tool, that is scheduled by the OS' task scheduler.
Since table structures and other database objects do not change that often (at least, not in production), you can use external tool to back up the structure and use the internal scheduled script to regularly back up the contents.

MySQL: Create stored procedures dynamically

I have a database to which several real users have access using JDBC. The separation of these users is very crucial, such that they are neither able see nor manipulate each other's data.
To separate the users' data, I decided to create the few corresponding tables for every user, and only give the owning user the permissions on this table. This is all done automatically in a stored procedure.
Besides this table separation, I want a user only to execute stored procedures to work with his tables, not arbitrary SQL queries.
Let's consider an example procedure like
DELIMITER //
CREATE PROCEDURE MyProcedure(IN p_identifier VARCHAR(30), IN p_key INT(10))
BEGIN
SET #p_identifier = p_identifier;
SET #p_key = p_key;
SET #s = CONCAT('DELETE FROM ', p_identifier, '_mytable WHERE key =?;');
PREPARE stmt FROM #s;
EXECUTE stmt USING #p_key,
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
And use it like CALL MyProcedure('ad3e981b', 2);.
So far, so good.
Problems arise since this procedure is used by all users (the first paraeter is the table-prefix). This is bad, because once a user gets execution privileges for MyProcedure, he is able to to provide any table-prefix at will and mess with other user's data - so my user separation is gone. This is the problem I need to solve.
I currently see two solutions:
Don’t use stored procedures: Just give INSERT/DELETE/SELECT privileges on the user's table only to the user. This is simple and works - but I'd prefer to only call stored procedures over JDBC, not arbitrary SQL queries.
Make a stored procedure for EVERY user, in which the table prefix is invariant (e.g, table-prefix_MyProcedure(), which is only executable by one user). Then, assign the execution privilege only to the corresponding user. However, this should be done automatically on request - hence, I need to be able to create a stored procedure with a parameterized name to set this up (phew). As the title suggests, this is the way I want to go - but I really struggle with the syntax of dynamically creating a stored procedure (in a stored procedure) and thus, I'm really not sure if this is how I should proceed.
Any ideas how I got approach this problem?
Regards,
raute

MySQL Stored procedure won't fetch the whole table

First I tried this, (MySQL/phpmyadmin)
CREATE DEFINER=`root`#`localhost` PROCEDURE `tempcheck`() NO SQL
BEGIN
SET #query_string = 'SELECT * FROM properties';
PREPARE query_statement FROM #query_string;
EXECUTE query_statement;
DEALLOCATE PREPARE query_statement;
END
This just fetches the first record of the table 'properties'. The table has more than one value. When I sqlquery 'select * from properties;' it returns the whole table.
I even tried this simple method
BEGIN
SELECT * FROM properties';
END
Tried many stackoverflow Q&As. They all suggest that I make a temp table. Even if I do, how will it return the whole table when it doesn't return the entire table here in the first place. CAN a mysql stored procedure actually return a whole table or NOT. if it can, then how?
Guys thank you all for your help. One of my colleagues helped me fix it. Apparently it's a bug in phpmyadmin. phpmyadmin won't return more than one record

What is the syntax for create table mytablename.now()?

i want to create a table and append NOW() to the end of the table name.
what would be the syntax please?
oops thank you for the correction.
My reason why i wat to do this is i have a script that runs on the database table everyday. If certain conditions are met i delete from the master table. BUT before i delete i just want to make a backup copy by running: create table rc_profile_backup_table_NOW() like rc_profile_table;
then i run: insert rc_profile_table_backup_NOW() select * from rc_profile_table
hope this is better.
thanks
Here is some rather ugly way to do it, using prepared statements. You might adjust the "now" part, because now makes invalid tables names I think.
set #c=concat('create table zogi_',date_format(now(),'%Y_%m_%d'),' (a varchar(10))');
prepare stmt from #c;
execute stmt;
deallocate prepare stmt
describe zogi_2012_02_07;
It creates a table named zogi_[year][month][day].