Solved

create MySQL table if not exists, ignore the talbe if it exists but still needs checking.

Posted on 2014-01-05
8
470 Views
Last Modified: 2014-01-08
right now I have the script to only create table if it doesn't exist:

CREATE PROCEDURE `create_auditriggers_forALL` (IN databaseName VARCHAR(40))  	
BEGIN  
DECLARE a, b, finished  INT DEFAULT 10;
DECLARE temptable VARCHAR(50);	
DECLARE today TIMESTAMP DEFAULT CURRENT_DATE;
DECLARE v1, v2, v3 TINYINT ;
DECLARE current_tablelist VARCHAR(50) DEFAULT ""; 
DECLARE fullexcutecmd VARCHAR(5000);
DECLARE fullexcutecmd2 VARCHAR(5000) ;
DECLARE BEFORE_DELETE TEXT  ;
DECLARE Final_BEFORE_DELETE TEXT DEFAULT "";
DECLARE AFTER_INSERT TEXT  ;
DECLARE Final_AFTER_INSERT TEXT DEFAULT ""  ;
DECLARE AFTER_UPDATE TEXT  ;
DECLARE Final_AFTER_UPDATE TEXT DEFAULT "";
DECLARE Check_Each_PrimaryKey_Autoincrement TEXT  ;
DECLARE Final_Check_Each_PrimaryKey_Autoincrement TEXT DEFAULT "";
DECLARE Check_index TEXT  ;
DECLARE Final_Check_index TEXT DEFAULT "";
 
 declare tablename CURSOR FOR 	

         SELECT  DISTINCT TABLE_NAME 	
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA=databaseName and table_type<> 'view' ;  
  

    
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;     
/*Specify what to do when no more records found, notice that the handler declaration must appear after variable and cursor declaration inside the stored procedures*/  	

OPEN tablename;	

	get_tabeslist: LOOP	
 
   FETCH tablename INTO current_tablelist;	
         IF finished = 1 THEN 	
          LEAVE  get_tabeslist;	
          END IF;	
  /* create the audit database's table */
  
SET @fullexcutecmd =CONCAT( 'CREATE TABLE IF NOT EXISTS Audit_info.',databaseName,'_DBAudit_', current_tablelist,' LIKE ',databaseName,'.',current_tablelist,';'); 
 
  PREPARE stmt FROM @fullexcutecmd;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;  


  END LOOP  get_tabeslist;	
close tablename;                             

END $$
DELIMITER ; 
    

Open in new window


but it seems that if I execute this SP more than one time, and it see the same table which was created, will give error message and stop.

Anyway to fix it ?
0
Comment
Question by:marrowyung
  • 5
  • 2
8 Comments
 
LVL 7

Expert Comment

by:Kishan Zunjare
ID: 39758499
0
 
LVL 1

Author Comment

by:marrowyung
ID: 39758594
I need more specific answer.
0
 
LVL 1

Author Comment

by:marrowyung
ID: 39758645
for example I can do this to BYPASS it by:


     SELECT  DISTINCT TABLE_NAME
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA='PCCWSP' and table_type <> 'view' and TABLE_NAME NOT IN ( SELECT  DISTINCT TABLE_NAME
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA='Audit_info' and table_type<> 'view');

Open in new window


as the condition of the cursor, but the result don't allow me to check all table name everytime but only the new one.

So I have to use that first one.
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
LVL 59

Accepted Solution

by:
Kevin Cross earned 500 total points
ID: 39759427
Maybe you can wrap the creation in an IF statement.  Although, it is not jumping out at me why the IF NOT EXISTS is not working as expected.  It may be helpful to SELECT the @fullexcutecmd variable and see what the CREATE TABLE looks like after the CONCAT to make sure it is nothing odd there.

Anyway, you can wrap the below lines in an IF:

DECLARE auditExistsFlag BIT(1);  
SET auditExistsFlag = 0;

SELECT 1 INTO auditExistsFlag
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA='Audit_info'
AND TABLE_NAME = CONCAT(databaseName,'_DBAudit_', current_tablelist)
;

IF auditExistsFlag = 0 THEN
  PREPARE stmt FROM @fullexcutecmd;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;  
END IF;

Open in new window


I hope that helps!
0
 
LVL 1

Author Comment

by:marrowyung
ID: 39761511
"Although, it is not jumping out at me why the IF NOT EXISTS is not working as expected"

exaction what I am thing, that's why I try to add the IF NOT EXISTS there but it don't works !!

"It may be helpful to SELECT the @fullexcutecmd variable and see what the CREATE TABLE looks like after the CONCAT to make sure it is nothing odd there.
"

this done at the beginning of this SP developement to troubleshoot everything ! MySQL is rubblish ! a lot of thing surprising DBA !

"SELECT 1 INTO auditExistsFlag"

why do this at the beginning and this variable never change to 1. And what is the main point of :

SELECT 1 INTO auditExistsFlag
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA='Audit_info'
AND TABLE_NAME = CONCAT(databaseName,'_DBAudit_', current_tablelist)

Open in new window

?
0
 
LVL 1

Author Comment

by:marrowyung
ID: 39761525
I think the IF should be:

SELECT count(*) INTO auditExistsFlag
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA='Audit_info'
AND TABLE_NAME = CONCAT(databaseName,'_DBAudit_', current_tablelist)
;

Open in new window


agree?
0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 39761607
COUNT(*) should work, but there is either one table or zero; therefore, the way I have it should also.  If it is not changing to 1, then it is not recognizing the existence of the audit table, which is why you are getting the error.
0
 
LVL 1

Author Closing Comment

by:marrowyung
ID: 39764615
thanks, I get it done already based on your suggsetion but I do this:

DECLARE TableExistsinAuditDB int (1) DEFAULT '0' ;
..
.
.
  SELECT count(*) INTO TableExistsinAuditDB    
FROM INFORMATION_SCHEMA.TABLES            
WHERE TABLE_SCHEMA='Audit_info'                        
AND TABLE_NAME = CONCAT(databaseName,'_DBAudit_', current_tablelist);  

if TableExistsinAuditDB < 1 then

.
.
.
.

END IF;
0

Featured Post

The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question