简体   繁体   中英

How to check number of rows before export the data in csv file from my sql table

this below query is working fine for me to export the data from table to csv file but i want handle like if query returns no record then in 'filename.csv' file should contain 'no data found' message for users

-- file name as timestamp
SET @fileName = DATE_FORMAT(NOW(),'%Y-%m-%d-%H:%i:%s');
SET @FOLDER = '/tmp/';
SET @EXT    = '.csv';

SET @CMD = CONCAT("SELECT id,name,salary,salaryDate FROM emp1 where name ='some_name' INTO OUTFILE '"
            ,@FOLDER,@fileName,@EXT,
            "' FIELDS ENCLOSED BY '\"' TERMINATED BY ',' ESCAPED BY '\"'",
            "  LINES TERMINATED BY '\n';"); 
PREPARE statement FROM @CMD;
EXECUTE statement;

where do i need to change ? Any one can help me ?

You should create stored procedure. Check row numbers using COUNT function, then output one of results you need, for example -

CREATE PROCEDURE procedure1()
BEGIN
  IF (SELECT COUNT(*) FROM emp1 where name ='some_name') = 0 THEN 
    SELECT 'no data found' INTO OUTFILE 'file_name.csv';
  ELSE
    your code here - SELECT INTO OUTFILE
  END IF;
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM