The invention discloses a text-to-
SQL (Structured
Query Language) generation and auditing method and device based on retrieval enhancement, and the method comprises the steps: analyzing a user intention by utilizing a generative Schema
routing model, and automatically selecting a
target database and a related table to form a query range; an example similar to the current question is retrieved from the historical question and answer corpus and serves as a Few-Shot prompt to be provided for the large
language model; then, self-adaptively constructing a joint prompt according to the difficulty of the problem, guiding the LLM to generate a preliminary
SQL query, and correcting an error through a cyclic feedback mechanism; an LLM-driven
SQL script automatic auditing and optimization suggestion module is introduced, comprehensive auditing is conducted on the generated SQL from the aspects of grammar specifications, query performance, structure optimization, safety protection and the like, and optimization suggestions are given out and serve as filtering and feedback links before the SQL falls into a
library. According to the method, retrieval enhancement and prompt generation technologies are fully combined, and the generation efficiency, reliability and safety are improved while the
correctness of the query result is ensured.