Stored procedure not able to read csv file through filepath via LOAD_FILE()

115 Views Asked by At

I want to create a stored procedure in mySQL workbench which reads a csv file from a path. I have made all required changes in my.ini file, set file path, secure_file_priv = "my/file/path", username is having 'file permission'. folder in which I have csv file that has read write/execution permission but still i m not able to make my SP read that csv file. csv file format is also checked thoroughly. In fact when i pass csv content statically, it runs perfectly but not able to read through file path. below is my basic Stored procedure. and my file path is "C:\ProgramData\MySQL\MySQL Server 8.0\Uploads"

CREATE DEFINER=`root`@`localhost` PROCEDURE `load_csv_file`(IN filePath VARCHAR(255))
BEGIN

DECLARE headerRow VARCHAR(500);
DECLARE columnIndex INT DEFAULT 1;
DECLARE columnName VARCHAR(100);

-- Read the CSV content from the file using LOAD_FILE function
SET headerRow = LOAD_FILE(filePath);

IF headerRow IS NOT NULL THEN
    -- Find the end index of the header row (first line of the CSV)
    SET headerRow = SUBSTRING_INDEX(headerRow, '\n', 1);
    
    -- Remove the header row from the CSV content
    SET headerRow = SUBSTRING(headerRow, CHAR_LENGTH(headerRow) + 2);
    
    -- Create a log table to store the headers (if it doesn't exist)
    CREATE TABLE IF NOT EXISTS header_log (
        id INT AUTO_INCREMENT PRIMARY KEY,
        header_name VARCHAR(100)
    );
    
    -- Loop through the header to extract the column names
    WHILE columnIndex > 0 DO
        SET headerRow = TRIM(headerRow);
        SET columnIndex = LOCATE(',', headerRow);
        
        -- Check if the column name is empty (end of header)
        IF columnIndex = 0 THEN
            SET columnName = headerRow;
        ELSE
            SET columnName = SUBSTRING(headerRow, 1, columnIndex - 1);
            SET headerRow = SUBSTRING(headerRow, columnIndex + 1);
        END IF;
        
        -- Insert the column name into the log table
        INSERT INTO header_log (header_name) VALUES (columnName);
    END WHILE;
    
    -- Send a message indicating that the headers have been extracted
    SELECT 'Headers extracted from CSV file successfully.' AS message;
ELSE
    -- If the file is not found or unable to read, send an error message
    SELECT 'Error: CSV file not found or unable to read.' AS message;
END IF;
END
 
0

There are 0 best solutions below