Method, device and equipment for generating SQL (Structured Query Language) statement based on natural language and storage medium
By performing semantic parsing and vector encoding on the natural language query instructions input by the user, combining the preset database and structured prompt templates to generate SQL statements, and performing syntax verification and permission verification, the accuracy and stability problems of SQL generation in the existing technology are solved, and efficient and intelligent data query and visual output are achieved.
Patent Information
- Application Number
- CN202510960328.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-07-11
- Publication Date
- 2025-10-17
AI Technical Summary
Existing technologies have problems when generating SQL statements, such as poor accuracy, ambiguous semantics that make it difficult to match database structures, lack of structured guidance mechanisms, high rates of grammatical and logical errors, and lack of authority control and interactive capabilities, resulting in a lack of visual output of query results.
By receiving natural language query instructions input by users, performing semantic parsing and vector encoding, using the preset vector database to obtain semantic enhancement information, filling it into the structured prompt template, generating SQL statements, and performing abstract syntax tree parsing and syntax verification, optimizing SQL statements, and combining permission verification and visual rendering.
It improves the accuracy and stability of SQL generation, provides efficient, intelligent, and interactive data query methods, ensures the semantic consistency of query results and user authority control, and supports multiple rounds of interactive queries and visual output.
Smart Images

Figure CN120804143A_ABST
Abstract
Description
TECHNICAL FIELD
[0001] The present application relates to the technical field of artificial intelligence, and in particular to a method and device for generating SQL statements based on natural language, an apparatus, and a storage medium. BACKGROUND
[0002] With the widespread application of database technology, the demand for data query by non-technical users is increasing. In order to simplify the threshold for using database query, the natural language generation SQL (Text2SQL) technology emerges as the times require, which aims to automatically generate and execute SQL statements by inputting natural language instructions, so as to obtain structured data results.
[0003] Current mainstream Text2SQL methods mostly rely on deep learning models, especially large language models (LLM), such as GPT-4, Claude, etc. These models can understand the natural language query intent and generate corresponding SQL statements based on pre-set prompts. However, the existing technology still has obvious deficiencies in the following aspects: Lack of context leads to poor accuracy: most existing methods directly call language models to generate SQL without context or with weak context, resulting in incomplete SQL structure, incorrect field selection, etc.
[0004] Semantic ambiguity is difficult to match database structure: the user's natural language expression has ambiguity or non-standard description, and the existing system is difficult to correctly map it to the actual field and table structure in the database.
[0005] Lack of structured guidance mechanism: the prompt input lacks standardization and slot design, making the generated results inconsistent and unreliable.
[0006] High error rate of SQL syntax and logic: large language models may generate SQL statements with correct syntax but incorrect semantics, or the generated fields do not exist in the target table, resulting in execution failure.
[0007] Query results lack visual output: even if the SQL is successfully generated, the user can only see the original table data, lacking intuitive display in the form of charts.
[0008] Lack of permission control and interaction ability: traditional systems cannot dynamically filter result fields according to user permissions, nor support subsequent instructions from users for error correction or optimization of query logic.
[0009] Therefore, the problems in the prior art need to be solved. SUMMARY
[0010] The application provides a method, device and equipment for generating SQL statements based on natural language and a storage medium, to solve the defects in the prior art and improve the accuracy and stability of SQL generation.
[0011] The application provides a method for generating SQL statements based on natural language, comprising: receiving a query instruction input by a user, the query instruction being in natural language; performing semantic analysis on the query instruction; performing semantic vector encoding on the query instruction and performing similarity retrieval in a preset vector database to obtain semantic enhancement information related to the query instruction; filling the semantic analysis result and the semantic enhancement information into a preset structured prompt template to obtain prompt input information; inputting the prompt input information into a large language model to generate an SQL statement.
[0012] According to the method for generating SQL statements based on natural language provided by the application, after the step of inputting the prompt input information into a large language model to generate an SQL statement, the method further comprises: performing abstract syntax tree analysis on the SQL statement to check whether the fields involved in the SQL statement exist in a target database structure and to match the types of the fields in the SQL statement; when the fields do not match or there is a semantic error, correcting the SQL statement according to a preset rule; rewriting the SQL statement and generating an optimized SQL statement based on a syntax verification and semantic feedback mechanism.
[0013] According to the method for generating SQL statements based on natural language provided by the application, after the step of rewriting the SQL statement and generating an optimized SQL statement based on a syntax verification and semantic feedback mechanism, the method further comprises: executing the SQL statement in a target database to obtain a structured query result; matching a target graph based on the data types and semantic information of the fields in the query result; rendering and visualizing the target graph.
[0014] According to the method for generating SQL statements based on natural language provided by the application, after the step of executing the SQL statement in a target database to obtain a structured query result, the method further comprises: performing permission verification on a query request of a user; if there is a field that the user has no access to in the query request, performing fuzzy processing on the field.
[0015] The method for generating an SQL statement based on natural language provided by the application further comprises the following steps after the step of rendering and visualizing the target chart: receiving a subsequent input query instruction of a user; correcting the generated SQL statement based on the subsequent input and context history information; re-executing the corrected SQL statement to obtain an updated query result; generating a corresponding chart display based on the updated query result.
[0016] The method for generating an SQL statement based on natural language provided by the application, wherein the structured prompt template comprises slot information, and the slot information is used to guide the large language model to generate an SQL statement; The method further comprises the following step before the step of filling the semantic analysis result and the semantic enhancement information into the preset structured prompt template to obtain prompt input information: When the slot information is missing or unclear, the missing slot information is completed based on context information, user historical query information or a preset default configuration.
[0017] The method for generating an SQL statement based on natural language provided by the application, wherein the step of performing semantic vector coding on the query instruction and performing similarity retrieval in a preset vector database to obtain semantic enhancement information related to the query instruction specifically comprises the following steps: converting the query instruction into a vector representation; performing similarity retrieval based on cosine similarity in a preset constructed vector database to obtain semantic enhancement information, wherein the semantic enhancement information comprises table structure, field semantic description, historical question and answer records and metadata; using the semantic enhancement information as context prompt information to guide SQL generation.
[0018] The application further provides a device for generating an SQL statement based on natural language, comprising: an instruction receiving module configured to receive a query instruction input by a user, wherein the query instruction is in natural language; an instruction analysis module configured to perform semantic analysis on the query instruction; an instruction coding module configured to perform semantic vector coding on the query instruction and perform similarity retrieval in a preset vector database to obtain semantic enhancement information related to the query instruction; a prompt generation module configured to fill a semantic analysis result and the semantic enhancement information into a preset structured prompt template to obtain prompt input information; The SQL statement generation module is configured to input the prompt input information into a large language model to generate a SQL statement.
[0019] The application further provides an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor, and the processor implements the method for generating a SQL statement based on a natural language according to any one of the above when executing the program.
[0020] The application further provides a non-transitory computer-readable storage medium having a computer program stored thereon, and the computer program is executable on a processor to implement the method for generating a SQL statement based on a natural language according to any one of the above.
[0021] The application further provides a computer program product including a computer program, and the computer program is executable on a processor to implement the method for generating a SQL statement based on a natural language according to any one of the above.
[0022] The application provides a method, device, equipment and storage medium for generating a SQL statement based on a natural language, which receives a query instruction input by a user, the query instruction being a natural language, performs semantic analysis on the query instruction, performs semantic vector coding on the query instruction, and performs similarity retrieval in a preset vector database to obtain semantic enhancement information related to the query instruction, fills the semantic analysis result and the semantic enhancement information into a preset structured prompt template to obtain prompt input information, and inputs the prompt input information into a large language model to generate a SQL statement. The application performs semantic analysis and vector coding on a natural language instruction input by a user, and combines a preset vector database to perform semantic enhancement, so that the generation process has context semantic support, and the consistency between the generation result and the user's intention is effectively improved. BRIEF DESCRIPTION OF DRAWINGS
[0023] In order to more clearly illustrate the technical solutions in the application or prior art, the following will briefly introduce the drawings needed in the embodiments or prior art description. Obviously, the drawings in the following description are some embodiments of the application, and for those skilled in the art, other drawings can also be obtained without creative labor.
[0024] Figure 1 is a flowchart of the method for generating a SQL statement based on a natural language provided by the application; Figure 2 is a structural diagram of the device for generating a SQL statement based on a natural language provided by the application; Figure 3 is a structural diagram of the electronic device provided by the application. DETAILED DESCRIPTION
[0025] The technical solutions in the present application will be described clearly and completely below with reference to the drawings in the present application. Obviously, the described embodiments are only some of the embodiments of the present application, but not all of them. Based on the embodiments in the present application, all other embodiments obtained by those of ordinary skill in the art without creative work fall within the protection scope of the present application.
[0026] To solve the problems in the prior art, the present application provides a method for generating SQL statements based on natural language to improve the accuracy and stability of SQL generation. The method for generating SQL statements based on natural language is described as follows, including but not limited to the following steps: Figure 1 Step 110, receiving a query instruction input by a user, the query instruction being a natural language.
[0027] In this step, a natural language input interface is provided for the user to input a query request, which is expressed in natural language. For example, the user can input "query the total sales of each category of goods in the past 7 days" as a query instruction. The system can receive the instruction through a Web page, a terminal program or an API interface, and input it as a natural language text to be processed.
[0028] Step 120, performing semantic analysis on the query instruction.
[0029] In step 120, the natural language instruction is preliminarily analyzed for semantic analysis, and key elements are extracted, including but not limited to: Entity information: such as "goods", "sales", "the past 7 days", etc. Intention information: such as "query", "statistics", "grouping", etc. Slot information: such as query field (sales), filtering condition (the past 7 days), grouping dimension (category), etc.
[0030] This process can be realized by combining natural language processing technologies such as named entity recognition (NER), dependency syntax analysis and keyword matching, to understand the structure and semantic composition of the query statement.
[0031] Step 130, performing semantic vector encoding on the query instruction, and performing similarity retrieval in a preset vector database to obtain semantic enhancement information related to the query instruction.
[0032] On the basis of semantic understanding, the system uses a semantic encoding model (such as OpenAI Embedding, BERT, BGE) to convert the natural language query instruction into a vector representation.
[0033] Subsequently, similarity retrieval is performed on the query vector in a pre-constructed vector database. The information stored in the vector database includes but is not limited to: Database table structure description (such as field name, field meaning); Historical question and answer records (Q&A pairs); Metadata information (such as index definition, data caliber description), etc.
[0034] Vector retrieval can be based on cosine similarity, inner product distance, etc. algorithm to obtain a number of enhanced information most relevant to the current query semantics. These information will be used to assist the subsequent SQL generation process, to improve the generation accuracy.
[0035] Step 140, filling the semantic parsing result and the semantic enhancement information into the preset structured prompt template to obtain prompt input information.
[0036] In the preset structured prompt template (Prompt template), multiple slots are reserved, such as target table name, field name, filter condition, grouping dimension, aggregation method, etc. The template has a fixed structure and uses a unified syntax format to guide the language model to generate the target SQL.
[0037] The slot information extracted in step 120 and the semantic enhancement information obtained in step 130 are correspondingly filled into the corresponding positions of the above template to form complete prompt input information (Prompt Input) for guiding the subsequent behavior of the large language model.
[0038] Step 150, inputting the prompt input information into the large language model to generate an SQL statement.
[0039] The above constructed prompt input information is input into the large language model (such as GPT-4, Claude, Wenxin Yiyang, etc.). The language model will automatically generate a corresponding structured query statement (SQL statement) based on the structured context content.
[0040] The present embodiment significantly improves the accuracy and stability of natural language generation of SQL statements through semantic parsing, semantic enhancement, and structured guidance, etc. multiple means, providing non-technical users with efficient, intelligent, and interactive data query means.
[0041] As a further optional embodiment, after the step of inputting the prompt input information into the large language model to generate an SQL statement, it further includes: Performing abstract syntax tree parsing on the SQL statement to check whether the fields involved in the SQL statement exist in the target database structure, and matching the types of the SQL statement fields; When the fields do not match or there is a semantic error, the SQL statement is corrected according to preset rules; Based on the syntax verification and semantic feedback mechanism, the SQL statement is rewritten and an optimized SQL statement is generated.
[0042] In this embodiment, when the large language model generates a SQL statement, the system calls a SQL parser to parse the SQL statement and generates an abstract syntax tree (AST) corresponding to the SQL statement. By traversing the syntax tree, all table names, field names, query conditions, aggregation functions, etc. contained in the SQL statement can be identified.
[0043] Subsequently, the system compares the field names with the database metadata (such as the field directory and the field type mapping table) to verify whether the fields actually exist in the table structure of the target database, and further verifies the field types, such as checking whether a string field is used for illegal operations such as numerical comparison, to ensure consistency in syntax and semantics.
[0044] When it is found that some field names in the SQL statement are misspelled, the field types are used improperly, or non-existent tables / fields are referenced, the system will automatically correct them according to the preset error correction rule library. For example: Using fuzzy matching or similarity sorting, the possible correct field names are recommended and the original fields are replaced; Template correction for common error patterns (such as mixing of strings and numbers, missing GROUP BY fields, etc.); Delete invalid statement segments and reconstruct the query logic.
[0045] The rule library can be maintained and updated by humans, and can also be automatically optimized in combination with user historical feedback.
[0046] After completing the syntax verification and correction, the system will generate a new version of the SQL statement. To ensure the correctness of the results, the optimized SQL statement will be structurally confirmed again by the abstract syntax tree.
[0047] In addition, the optimization process also supports the introduction of model feedback mechanism, that is, the identified error types are taken as additional input, together with the original query intent Figure 1 to form a new Prompt, and input the large language model again to rewrite the SQL, so as to generate a final SQL result with more semantic accuracy.
[0048] Finally, the system outputs a SQL statement with complete structure, legal fields, and clear semantics, ensuring that it can be correctly executed in the target database, maximizing the user query experience and the fault tolerance of the system.
[0049] As a further optional embodiment, in the syntax-based verification and semantic feedback mechanism, after the step of rewriting and generating an optimized SQL statement, the method further comprises: executing the SQL statement in the target database to obtain a structured query result; matching a target chart based on the data type and semantic information of the fields in the query result; rendering and visualizing the target chart.
[0050] In this embodiment, after the SQL statement passes the syntax and semantic verification and is optimized, the system submits the SQL statement to a target database system (such as MySQL, PostgreSQL, ClickHouse, etc.) for execution. The execution result is returned in the form of a structured data table, usually containing several column fields and corresponding multiple rows of data.
[0051] To ensure query security, access permission control logic can be embedded in this step, such as verifying whether the user has access permission to the current data source or field to prevent sensitive data leakage.
[0052] The system analyzes the returned structured query result and extracts the following elements: the data type of each field (such as integer, floating point, timestamp, string, etc.); the semantic role of the field (such as dimension field, metric field, time field); data row count, value range, field uniqueness, and other statistical characteristics.
[0053] Based on the above analysis results and combined with the query intent, the system automatically determines the most suitable visualization chart type through a chart recommendation algorithm. Example matching logic includes but is not limited to: time field + numerical field → line chart; category field + numerical field → column chart, bar chart; single numerical field total proportion → pie chart; relationship between two numerical fields → scatter plot; table structure → data table.
[0054] This recommendation process can be implemented through pre-set rules, heuristic algorithms, or trained models to improve the intuitiveness and semantic compatibility of the display effect.
[0055] Using a chart rendering component (such as ECharts, Chart.js, Highcharts, etc. open source chart library), the matched chart type is bound to the corresponding data and rendered as a visual graph. The chart supports display in the front-end page, mobile application or integrated system, and can also be exported in PNG, SVG, PDF, etc. format.
[0056] In addition, the chart component supports user interaction, such as hovering, filtering, zooming, click linkage, etc. operations, enhancing the analysis capability and user experience.
[0057] This step realizes the closed loop from natural language input to structured query result graphical presentation, effectively supporting non-technical users to explore and understand data independently.
[0058] As a further optional embodiment, after the step of executing the SQL statement in the target database to obtain the structured query result, it further comprises: checking the permission of the user's query request; If there is a field in the query request that the user has no access to, the field is processed by the fuzzy processing.
[0059] After executing the SQL statement and obtaining the structured query result, the system further performs permission checking operation on the query request to ensure that the data content requested by the user is within the scope of his access permission. Specifically, the system judges whether the field involved in the current query belongs to the authorized range of the user based on the user identity information (such as user ID, role type, and affiliated organization) and the preset permission policy (such as field-level, table-level, and data source-level permission configuration).
[0060] The permission checking module can be integrated with enterprise-level permission systems (such as LDAP, SSO, and OAuth platform) to support dynamic permission acquisition and real-time checking.
[0061] After completing the permission check, if there is a sensitive field in the field or table requested by the user that the user has no access to, the system will not directly throw an error or interrupt the query, but will perform desensitization display through the fuzzy processing mechanism to improve user experience and protect data security.
[0062] The fuzzy processing method includes but is not limited to: Replace the real data with "***" or "invisible field"; Fuzzing numerical fields to intervals (such as "1000-5000"); Fuzzing precise time fields to dates (such as "2024-06-12 15:33:21" → "June 2024"); Some fields are masked (e.g., “Zhang San” -> “Zhang *”).
[0063] In addition, for auditability, the system records the field de-identification operation in the log for future traceability.
[0064] Through this embodiment, it can be ensured that while meeting data access compliance, as much reference information as possible is provided to the user, and it is suitable for enterprise-level data query platforms, BI tools, data middle platforms, etc.
[0065] As a further optional embodiment, after the step of rendering and visualizing the target chart, it further includes: receiving the user's subsequent input query instruction; based on the subsequent input and the context history information, correcting the generated SQL statement; re-executing the corrected SQL statement to obtain updated query results; generating a corresponding chart display based on the updated query results.
[0066] In this embodiment, the system supports multi-round interactive query. After completing the chart visualization of the initial query results, it continues to listen to and receive the user's subsequent input. For example, the user may input natural language instructions such as “subdivide the category again”, “sort by province”, “change the chart to see”, etc. These inputs can be incremental information, modification instructions or optimization requirements.
[0067] The system regards these subsequent instructions as part of the continuous session and processes them in association with the current session context.
[0068] The system maintains a dialogue context management module to record the historical query content of the current user session, including: the original natural language instruction; the SQL statement that has been generated and executed; the current used fields, filtering conditions and chart type, etc.
[0069] After the user's subsequent input arrives, the system performs semantic understanding on the instruction and automatically infers the SQL structure that needs to be modified or appended in combination with the context. For example: If the user inputs “subdivide by region again”, the system adds GROUP BY region to the current SQL; If the user inputs “change to line chart”, only the chart display method is updated; If the user inputs “change to sales”, the SELECT field is replaced with “sales”.
[0070] The revised natural language instruction is re-input into the large language model through a structured prompt template to generate an updated SQL statement.
[0071] The system submits the revised SQL statement to the target database for re-execution to obtain structured data results matching the new query logic.
[0072] To ensure accuracy, the system still checks the SQL structure before and after execution and performs semantic verification. If there are field errors, permission boundary violations, etc., feedback is provided and correction is prompted.
[0073] The system re-triggers the chart recommendation logic based on the new query result data to determine the most suitable chart type and render it. The newly generated chart will overwrite the previous chart display, or start a new page as set by the user for comparison and viewing.
[0074] The entire process constitutes a closed loop of interactive SQL generation and visualization update, significantly improving the usability and intelligence level of natural language query systems in multi-round dialogue and complex exploration scenarios.
[0075] As a further optional embodiment, the structured prompt template includes slot information for guiding the large language model to generate the SQL statement. Before the step of filling the semantic parsing result and the semantic enhancement information into the preset structured prompt template to obtain prompt input information, it further includes: When the slot information is missing or unclear, the missing slot information is completed based on context information, user historical query information, or a preset default configuration.
[0076] In this embodiment, before filling the semantic information into the structured prompt template, the system first performs integrity detection on the extracted slot information. Slot information refers to the core components required for SQL generation, including but not limited to: Target table of the query (e.g., order table, customer table); Query fields (e.g., sales, order time); Filter conditions (e.g., within 30 days, amount greater than 1000); Aggregation operations (e.g., SUM, COUNT, AVG); Grouping dimensions or sorting fields, etc.
[0077] If the system detects that some slots are missing or expressed unclearly, for example, the user only inputs "see customer report" without specifying fields or time range, the completion process is entered.
[0078] To ensure the integrity of the generated prompt input information, the system designs various slot completion strategies: Context information completion: If the query is a subsequent round in a multi-round dialogue, the system will automatically inherit the previous table name, filtering conditions, and other slot content based on the historical query information in the current session. For example, if the user queried "last month's sales" in the previous round, the system will automatically fill in "last month" in the filtering conditions in this round.
[0079] User historical query record completion: The system can extract default table names or aggregate fields from the user's past queries based on their historical questioning habits or commonly used fields, and provide intelligent recommendations and completions.
[0080] Default configuration completion: If the context information is insufficient, the system can perform default completion based on domain knowledge or system preset logic, for example: No time range specified → Default query for the last 30 days; No aggregate field specified → Default to show total or average; No sorting method specified → Default to sort by time in descending order.
[0081] The above completion strategies can be used alone or in combination to ensure that the required prompt input information is complete and clear in each SQL generation request.
[0082] After the slot information completion is completed, the system fills the completed semantic parsing results and semantic enhancement information into the structured prompt template, generating complete prompt input information for the large language model to generate structured and accurate SQL statements.
[0083] Through this implementation, even if the user's natural language expression is incomplete, the system can guide the model to correctly understand the intent through intelligent completion mechanisms, significantly improving query success rate and user experience.
[0084] As a further optional embodiment, the step of encoding the query instruction into a semantic vector and performing similarity retrieval in a preset vector database to obtain semantic enhancement information related to the query instruction specifically includes: Convert the query instruction into a vector representation; In the preset constructed vector database, perform similarity retrieval based on cosine similarity to obtain semantic enhancement information, including table structure, field semantic description, historical question and answer records, and metadata; Use the semantic enhancement information as context prompt information to guide SQL generation.
[0085] In this embodiment, first, the system uses an embedding model (such as OpenAI Embedding, BERT, BGE (BAAI General Embedding), etc. semantic encoding model) to encode the natural language query instruction input by the user, and convert it into a fixed-dimensional semantic vector. The semantic vector can represent the context semantics of the query content and is suitable for subsequent similarity matching.
[0086] For example, the user inputs "the total order amount of each user in the past month", and the system encodes this sentence into a high-dimensional floating-point vector [v1, v2,..., vn].
[0087] The system constructs a vector retrieval library containing database structure information in advance based on FAISS, Milvus, or other vector databases. The library stores semantic vectors corresponding to the following information: Structure description of each data table (table name, field name, primary-foreign key relationship, etc.); Semantic explanation, example value, and data type of each field; Historical user question and answer pairs (natural language questions and generated SQL); Data meta information (such as data caliber, field unit, index definition, etc.).
[0088] The system performs similarity calculation on the user query semantic vector and all vectors in the above library, preferably using cosine similarity as the measurement method, and selects several results with high similarity ranking as semantic enhancement information output.
[0089] The obtained semantic enhancement information will be used as a supplementary prompt context, and will be filled into the structured prompt template together with the semantic analysis result to form complete prompt input information.
[0090] For example: If the user does not explicitly indicate which table to use, the "order table" vector that best matches the user's intention may be retrieved; If the user says "look at the sales", and the field name is order_amount, the correct field can be associated through the field semantic vector; If there are similar questions in the historical question and answer records, they can be used as a prompt to guide the current SQL generation logic.
[0091] Through this mechanism, the system can effectively enhance the understanding ability of the large language model for the query background, and improve the accuracy, rationality, and stability of the generated SQL statements.
[0092] The device for generating SQL statements based on natural language provided by the present application is described as follows: Figure 2As shown, the device for generating SQL statements based on natural language described below can correspond to the method for generating SQL statements based on natural language described above.
[0093] A device for generating SQL statements based on natural language, comprising: An instruction receiving module 210 for receiving a query instruction input by a user, the query instruction being natural language; An instruction parsing module 220 for performing semantic parsing on the query instruction; An instruction encoding module 230 for performing semantic vector encoding on the query instruction and performing similarity retrieval in a preset vector database to obtain semantic enhancement information related to the query instruction; A prompt generating module 240 for filling the semantic parsing result and the semantic enhancement information into a preset structured prompt template to obtain prompt input information; An SQL statement generating module 250 for inputting the prompt input information into a large language model to generate an SQL statement.
[0094] Figure 3 An example of an entity structure diagram of an electronic device is shown in FIG. 1. Figure 3 As shown, the electronic device can include a processor 310, a communications interface 320, a memory 330, and a communications bus 340, wherein the processor 310, the communications interface 320, and the memory 330 communicate with each other through the communications bus 340. The processor 310 can invoke logical instructions in the memory 330 to execute a method for generating SQL statements based on natural language, the method comprising: receiving a query instruction input by a user, the query instruction being natural language; performing semantic parsing on the query instruction; performing semantic vector encoding on the query instruction and performing similarity retrieval in a preset vector database to obtain semantic enhancement information related to the query instruction; filling the semantic parsing result and the semantic enhancement information into a preset structured prompt template to obtain prompt input information; inputting the prompt input information into a large language model to generate an SQL statement.
[0095] In addition, the logic instructions in the memory 330 described above can be implemented in the form of a software function unit and sold or used as an independent product, which can be stored in a computer readable storage medium. Based on such understanding, the technical solutions of the present application essentially or the parts that contribute to the prior art or parts of the technical solutions can be embodied in the form of a software product. The computer software product is stored in a storage medium, and includes several instructions for making a computer device (which can be a personal computer, a server, or a network device, etc.) execute all or part of the steps of the methods described in various embodiments of the present application. The aforementioned storage medium includes: a U disk, a mobile hard disk, a read-only memory (ROM, Read-Only Memory), a random access memory (RAM, Random Access Memory), a magnetic disk or an optical disk, and various media that can store program codes.
[0096] In another aspect, the present application also provides a computer program product, which comprises a computer program, the computer program can be stored on a non-transitory computer readable storage medium, and the computer program can be executed by a processor to enable a computer to execute the method for generating an SQL statement based on a natural language provided by the above-mentioned methods, which comprises: receiving a query instruction input by a user, the query instruction being a natural language; performing semantic analysis on the query instruction; performing semantic vector coding on the query instruction, and performing similarity retrieval in a preset vector database to obtain semantic enhancement information related to the query instruction; filling the semantic analysis result and the semantic enhancement information into a preset structured prompt template to obtain prompt input information; inputting the prompt input information into a large language model to generate an SQL statement.
[0097] In another aspect, the present application also provides a non-transitory computer readable storage medium, which stores a computer program, the computer program is executed by a processor to implement the method for generating an SQL statement based on a natural language provided by the above-mentioned methods, which comprises: receiving a query instruction input by a user, the query instruction being a natural language; performing semantic analysis on the query instruction; performing semantic vector coding on the query instruction, and performing similarity retrieval in a preset vector database to obtain semantic enhancement information related to the query instruction; filling the semantic analysis result and the semantic enhancement information into a preset structured prompt template to obtain prompt input information; The prompt input information is input into a large language model to generate an SQL statement.
[0098] The device embodiments described above are merely illustrative, wherein the units illustrated as separate components can or can not be physically separated, and the components illustrated as units can or can not be physical units, i.e., can be located in one place or distributed on multiple network units. Part or all of the modules can be selected to achieve the purpose of the embodiment scheme according to actual needs. Those skilled in the art can understand and implement without creative labor.
[0099] Through the description of the above embodiments, those skilled in the art can clearly understand that the embodiments can be realized by means of software and the necessary general hardware platform, and of course can also be realized by hardware. Based on such understanding, the above technical solutions can be embodied in the form of a software product, which can be stored in a computer readable storage medium, such as a ROM / RAM, a magnetic disk, an optical disk, etc., and includes a number of instructions to make a computer device (which can be a personal computer, a server, or a network device, etc.) execute the methods described in each embodiment or some parts of the embodiments.
[0100] Finally, it should be noted that: the above embodiments are only used to illustrate the technical solutions of the present application, and not to limit them; although the present application has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that: it can still modify the technical solutions recorded in the foregoing embodiments, or make equivalent replacement for part of the technical features; and these modifications or replacements do not make the essence of the corresponding technical solutions deviate from the spirit and scope of the technical solutions of the embodiments of the present application.
Claims
1. A method for generating SQL statements based on natural language, characterized in that: include: receiving a query instruction input by a user, wherein the query instruction is in natural language; Performing semantic analysis on the query instruction; Performing semantic vector encoding on the query instruction and performing similarity search in a preset vector database to obtain semantic enhancement information related to the query instruction; Filling the semantic parsing result and the semantic enhancement information into a preset structured prompt template to obtain prompt input information; The prompt input information is input into a large language model to generate an SQL statement.
2. The method for generating SQL statements based on natural language according to claim 1, characterized in that: After the step of inputting the prompt input information into the large language model to generate an SQL statement, the method further includes: Performing abstract syntax tree parsing on the SQL statement to verify whether the fields involved in the SQL statement exist in the target database structure and matching the types of the SQL statement fields; When there is a field mismatch or semantic error, the SQL statement is corrected using preset rules; Based on syntax verification and semantic feedback mechanism, SQL statements are rewritten and optimized SQL statements are generated.
3. The method for generating SQL statements based on natural language according to claim 2, characterized in that: After the step of rewriting the SQL statement and generating an optimized SQL statement based on the syntax verification and semantic feedback mechanism, the following steps are also included: Execute the SQL statement in the target database to obtain structured query results; Matching a target graph based on the data type and semantic information of the fields in the query result; Render and visualize the target graph.
4. The method for generating SQL statements based on natural language according to claim 3, characterized in that: After the step of executing the SQL statement in the target database to obtain a structured query result, the method further includes: Perform permission verification on user query requests; If the query request contains fields that the user does not have permission to access, the fields are obfuscated.
5. The method for generating SQL statements based on natural language according to claim 3, characterized in that: After the step of rendering and visualizing the target chart, the method further includes: Receive query instructions subsequently input by the user; Based on the subsequent input and the contextual history information, the generated SQL statement is modified; Re-execute the corrected SQL statement to obtain the updated query results; Generate corresponding chart displays based on the updated query results.
6. The method for generating SQL statements based on natural language according to claim 1, characterized in that: The structured prompt template includes slot information, and the slot information is used to guide the large language model to generate SQL statements; Before the step of filling the semantic parsing result and the semantic enhancement information into a preset structured prompt template to obtain prompt input information, the method further includes: When slot information is missing or unclear, the missing slot information is completed based on context information, user historical query information, or preset default configuration.
7. The method for generating SQL statements based on natural language according to claim 1, characterized in that: The step of encoding the query instruction with a semantic vector and performing a similarity search in a preset vector database to obtain semantic enhancement information related to the query instruction specifically includes: Converting the query instruction into a vector representation; In a pre-built vector database, similarity retrieval is performed based on cosine similarity to obtain semantic enhancement information, which includes table structure, field semantic description, historical question and answer records, and metadata; The semantic enhancement information is used as contextual prompt information to guide SQL generation.
8. A device for generating SQL statements based on natural language, characterized in that: include: An instruction receiving module is used to receive a query instruction input by a user, wherein the query instruction is in natural language; An instruction parsing module, used for performing semantic parsing on the query instruction; An instruction encoding module is used to perform semantic vector encoding on the query instruction and perform similarity search in a preset vector database to obtain semantic enhancement information related to the query instruction; A prompt generation module, configured to fill the semantic parsing result and the semantic enhancement information into a preset structured prompt template to obtain prompt input information; The SQL statement generation module is used to input the prompt input information into the large language model to generate SQL statements.
9. An electronic device comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein: When the processor executes the program, the method for generating SQL based on natural language according to any one of claims 1 to 7 is implemented.
10. A non-transitory computer-readable storage medium having a computer program stored thereon, characterized in that: When the computer program is executed by a processor, the method for generating SQL based on natural language according to any one of claims 1 to 7 is implemented.
Citation Information
Cited By
Text2SQL (Structured Query Language) caching method and system based on semantics
CN121210524A
SQL (Structured Query Language) generation method, system and equipment based on double engines and medium
CN121455975A
Query statement generation method and device, equipment, medium and program product
CN121524328A
Score query method and device, electronic equipment and storage medium
CN121705296A
DLF-based production system-oriented AI trusted data inquiry device
CN122284973A