A training method, apparatus, device, and storage medium for a natural language to SQL model.

CN122571102APending Publication Date: 2026-08-14ANT BLOCKCHAIN TECHNOLOGY (SHANGHAI) CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202610696501.0
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-05-19
Publication Date
2026-08-14

AI Technical Summary

Technical Problem

[0015]本发明一个实施例提供一种自然语言转SQL模型的训练方法、装置、设备及存储介质,用于缓解现有自然语言转SQL训练方案中对多方言数据库环境建模不足、执行层反馈利用不足以及复杂输入条件下训练样本稳定性不足的问题

Benefits of technology

[0026]采用上述技术方案后,围绕同一数据库实例构建分别对应于至少两种SQL方言环境的数据库执行环境,并在不同SQL方言环境下对候选SQL样本进行执行校验,可以使训练样本在进入模型训练之前包含数据库环境约束和执行结果约束,从而降低模型仅依赖单一方言表达进行学习的情况。将执行反馈信息用于样本筛选、样本标注、样本调整以及模型参数更新,可以使训练目标更接近目标数据库环境中的可执行性和结果正确性。通过构建辅助上下文信息并在其中加入干扰信息,还可以使训练过程覆盖更接近实际部署条件的输入形态,从而提高自然语言转SQL模型在多方言数据库环境下的可执行性、结果一致性以及复杂输入条件下的稳定性。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122571102A_ABST
    Figure CN122571102A_ABST
Patent Text Reader

Abstract

This invention relates to the field of natural language to database query technology, and discloses a training method, apparatus, device, and storage medium for a natural language to SQL model. The method includes: acquiring a database instance and constructing database execution environments corresponding to at least two SQL dialect environments based on the database instance; generating baseline SQL samples corresponding to the query task and natural language samples semantically corresponding to the baseline SQL samples; generating candidate SQL samples based on at least two SQL dialect environments; performing execution verification on the candidate SQL samples to obtain execution feedback information; performing sample filtering, sample labeling, or sample adjustment based on the execution feedback information to obtain training samples; training the natural language to SQL model using the training samples, and constructing training feedback based on the execution feedback information to update the model parameters. This approach can improve the executability and result consistency of the natural language to SQL model in multi-dialect database environments.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of natural language to database query technology, specifically to a training method, apparatus, device, and storage medium for a natural language to SQL model. Background Technology

[0002] Natural Language-to-SQL (NLP) technology is typically used to convert user-inputted natural language queries into structured query statements that can be executed in the target database to retrieve the desired results from a relational database. This technology involves multiple stages, including natural language understanding, database schema parsing, query generation, and query result validation, and has become a crucial foundational capability in intelligent data analysis, interactive data retrieval, and intelligent database operation and maintenance. In enterprise-level applications, users often do not directly understand the database table structure, field names, or the specific syntax of the database query language. Instead, they describe their query requirements in everyday language. Therefore, the model needs to understand the query intent based on the natural language content and generate corresponding SQL statements by combining this information with the database schema.

[0003] For Natural Language to SQL (NLP) tasks, training data typically contains at least three types of information: database-related information, the natural language question, and the target SQL statement. Database-related information can include table structure, field names, field types, primary and foreign key relationships, and sample data. The natural language question describes the data conditions and statistical methods the user expects to obtain. The target SQL statement represents the executable query logic corresponding to the natural language question. During training, the model typically learns the correspondence between natural language and database schemas, as well as the mapping between natural language and SQL structures, thereby generating candidate SQL statements based on new natural language input during the inference phase. Because the generated SQL statements not only need to semantically match the user's intent as closely as possible but also need to satisfy the grammatical rules of the target database system and be executable in the target database environment, this task places higher demands on the quality of training data and the design of training objectives compared to general text generation tasks.

[0004] In existing technologies, a common approach is to construct paired samples of natural language questions and SQL statements based on publicly available datasets, and then conduct supervised training of the model using database schema information. This approach is advantageous because its implementation path is relatively direct and the training process is relatively easy to establish, thus it is widely used for the initial construction of natural language to SQL models. However, the database size, schema type, and query logic in publicly available datasets usually have certain boundaries, and their natural language expressions often revolve around standardized question formats. When model training primarily relies on these samples, the model tends to learn mapping patterns within the existing data distribution more easily, but its adaptability to complex database structures, cross-table statistical logic, and non-standardized question formats common in enterprise-level scenarios still has room for improvement. Especially in business systems, the relationships between database tables, field naming styles, time calibers, and business calibers are often more complex. If the training samples do not adequately cover these factors, the model is prone to issues such as field location errors, missing join conditions, or incomplete aggregation logic during the inference phase.

[0005] Building upon this, existing technologies have attempted to improve model generalization capabilities by constructing larger-scale synthetic samples. Such approaches typically automatically generate query statements based on database schemas, then generate natural language questions for these queries, thereby reducing manual annotation costs and increasing the number of training samples. For natural language to SQL tasks, synthetic data can, to some extent, expand the range of database schemas and SQL structures, allowing the model to encounter more types of query expressions. However, when the synthesis process primarily focuses on the result of "generating question-SQL matching samples," the sample construction process often prioritizes semantic readability or structural diversity, while paying relatively little attention to whether the samples truly adapt to the target database environment, whether they maintain consistent execution logic across different database dialects, and whether the samples have layered coverage capabilities for complex scenarios. In other words, simply increasing the sample size does not necessarily guarantee a stable improvement in the model's performance on real database systems.

[0006] From the perspective of database execution environment, enterprise-level natural language to SQL systems are typically not designed for a single database product. Different business systems may use multiple relational databases in parallel, or use database engines compatible with different SQL dialects. These different database dialects usually refer to the differences in how different database systems implement Structured Query Language (SCL) in terms of syntax rules, function calls, type handling, and execution constraints. Therefore, the same query intent often corresponds to different SQL syntax in different database environments. Even if these database systems all support Structured Query Language, their function names, expression forms, string handling methods, date handling methods, pagination methods, null value handling methods, and support for common table expressions may differ.

[0007] Therefore, the same query intent, when applied to different database environments, often results in SQL statements that adhere to different grammatical constraints. If the training phase primarily builds samples based on a single database environment, the model tends to learn generation patterns specific to that single dialect. During the inference phase, when the input database environment changes, even if the natural language problem and database pattern remain similar, the model may still use the grammatical structure of the original dialect. This can lead to the generated results being unexecutable in the target database, or, although executable, deviating from the target semantics.

[0008] Further analysis reveals that existing training sample organization often emphasizes the correspondence between natural language and SQL text, while neglecting to fully address the crucial question of whether the SQL can be correctly executed in the target database. Since SQL statements can have multiple semantically equivalent but different textual forms, if the training process primarily relies on text-level alignment—for example, comparing the generated SQL with the character or word sequences of a reference SQL—the training objective is more likely to prioritize "writing like the reference answer" rather than effectively constraining whether the generated SQL is valid in the actual database. For natural language to SQL conversion tasks, the factors truly affecting system usability include not only the standardization of the SQL text but also whether the generated SQL references existing tables and fields in a given database schema, meets dialect grammatical requirements, and returns results consistent with the target semantics after execution. If the training process fails to fully incorporate this execution-level information into sample selection and model optimization, the model may learn more superficial patterns but less execution constraints directly related to the database environment.

[0009] In existing technologies, another approach involves executing and validating the SQL statements generated by the model during the inference phase, or rearranging, correcting, or filtering candidate SQL statements based on the execution results. This approach can, to some extent, utilize database execution feedback to suppress obviously erroneous candidate results, thereby improving the quality of the terminal output. However, this method mainly occurs during the inference phase, and is more of a post-hoc patching of the generated results. If the training phase still relies primarily on static samples, without systematically moving execution feedback forward into the training data construction and model optimization process, the model parameters themselves may not fully learn the stable patterns related to database execution. In other words, while execution correction during the inference phase can alleviate some errors, it still requires generating candidate SQL statements first, and then identifying and correcting problems through additional steps. This easily increases the complexity of the inference chain and is unlikely to fundamentally improve the original generation quality of the model in complex scenarios.

[0010] Besides database dialect differences and execution-level constraints, inconsistencies between real user input and training sample expressions also impact natural language to SQL models. In public and partially synthetic datasets, natural language problems typically employ standardized written expressions with complete entity names, explicit conditional relationships, and stable sentence structures. However, in real-world systems, users may use colloquial, abbreviated, vague, or context-dependent expressions. For example, users might not explicitly provide standard database field names but instead use business slang, time abbreviations, or incomplete conditions to express their query needs; they might also mix filtering conditions, statistical objects, and time ranges within the same sentence. For the model, such input doesn't necessarily change the query intent itself, but it makes intent recognition and field mapping more dependent on the expression distribution seen during training. If the natural language expression style in the training samples is relatively uniform, the model may easily misinterpret surface differences as semantic differences when faced with different expressions, thus affecting subsequent SQL structure generation.

[0011] To mitigate this issue, existing solutions sometimes augment natural language questions with data, such as rewriting the question format, replacing synonyms, or constructing expressions with different styles. These augmentations help expand the surface distribution of the natural language input, allowing the model to adapt to a wider range of input expressions. However, for natural language to SQL tasks, simply adding a few rewritten natural language samples may not be sufficient to cover the complex contextual conditions encountered during actual training and deployment. This is because, in real-world applications, models often receive auxiliary context in addition to natural language questions, such as database schema summaries, field value hints, relevant examples, and even historical experience information. This auxiliary information plays a role in helping the model locate fields and complete semantics, but it may also contain irrelevant, redundant, or similar but incorrect hints. If the auxiliary context is always accurate and interference-free during training, the model may become overly reliant on these hints; once the context construction in the deployment environment is noisy, the model is prone to attention shifts, thus affecting the stability of SQL generation.

[0012] From the perspective of training system construction, current solutions often focus on specific aspects of data synthesis, multi-dialect adaptation, execution verification, or robustness enhancement, but rarely organize these stages as a unified training pipeline. In other words, data construction is typically handled by one process, execution feedback by another, and multi-dialect processing and context enhancement may rely on independent modules. While this approach may improve certain aspects, intermediate results between different stages may not be fully reusable. For example, if multi-dialect executable samples for the same query task are not generated during the data construction phase, even with the introduction of execution feedback in subsequent training stages, it will be difficult to directly learn the constraint differences between different dialects. Similarly, if no perturbative auxiliary context is introduced into the training samples, even after filtering out obviously erroneous samples through execution results, the model's robustness to complex contexts may still be insufficient. Therefore, in the training process of natural language to SQL models, there is a strong correlation between sample construction, execution verification, dialect adaptation, and context robustness. Optimizing only one stage in isolation often fails to simultaneously ensure the model's execution accuracy, dialect consistency, and stability under complex input conditions.

[0013] Based on the above analysis, it can be seen that existing technologies still have room for improvement in training Natural Language to SQL models. In summary, there are at least the following problems: First, existing training sample construction methods often rarely perform multi-dialect parallel modeling of the same database task during the training phase, resulting in insufficient model adaptability to different SQL dialects. This leads to syntactic or semantic deviations in the generated results across different database environments. Second, existing training processes rely heavily on the static correspondence between natural language and SQL text. Feedback information at the execution level is not sufficiently moved forward and integrated into training data selection and model optimization, making it difficult to stably constrain the true executability and correctness of the generated SQL. Third, existing sample augmentation typically focuses more on rewriting the natural language problem itself, while insufficiently modeling interference information in the auxiliary context, leaving room for improvement in the model's robustness under complex prompting conditions.

[0014] Therefore, a new training scheme for natural language to SQL models is needed to establish a parallel sample construction and execution verification mechanism for at least two SQL dialect environments during the training phase, and to further use the execution feedback for training sample optimization and model training. At the same time, it should be combined with the robustness enhancement of auxiliary context to improve the generation quality and execution stability of natural language to SQL models in complex query scenarios, multi-dialect database environments, and under conditions with interference context. Summary of the Invention

[0015] One embodiment of the present invention provides a training method, apparatus, device, and storage medium for a natural language to SQL model, which is used to alleviate the problems of insufficient modeling of multi-dialect database environments, insufficient utilization of execution layer feedback, and insufficient stability of training samples under complex input conditions in existing natural language to SQL training schemes.

[0016] One embodiment of the present invention provides a training method for a natural language to SQL model, applied to a database execution environment corresponding to at least two SQL dialect environments. The training method includes: obtaining a database instance and constructing a database execution environment corresponding to the at least two SQL dialect environments based on the database instance; generating a baseline SQL sample corresponding to a query task and a natural language sample semantically corresponding to the baseline SQL sample based on the database instance; generating candidate SQL samples in the corresponding SQL dialect environments based on the at least two SQL dialect environments; sending the candidate SQL samples to the corresponding database execution environments for execution verification to obtain execution feedback information, the execution feedback information including at least one of execution status information and execution result information; performing sample screening, sample labeling, or sample adjustment on the natural language samples, the baseline SQL samples, and the candidate SQL samples based on the execution feedback information to obtain training samples; training the natural language to SQL model using the training samples, and constructing training feedback based on the execution feedback information during the training process to update the parameters of the natural language to SQL model.

[0017] In one embodiment, constructing a database execution environment corresponding to the at least two SQL dialect environments based on the database instance includes: generating table creation statements and data writing statements suitable for the at least two SQL dialect environments according to the table structure and data content of the database instance; and establishing a database execution environment in the corresponding database system based on the table creation statements and the data writing statements.

[0018] In one embodiment, generating a baseline SQL sample corresponding to the query task based on the database instance, and a natural language sample corresponding to the semantics of the baseline SQL sample, includes: generating baseline SQL samples of different difficulty levels according to a preset complexity rule; and generating at least two natural language samples with semantically equivalent expressions to each baseline SQL sample for each baseline SQL sample.

[0019] In one embodiment, the execution feedback information includes at least one of the following: execution success information or execution failure information of the candidate SQL sample in the corresponding database execution environment; result set information of the candidate SQL sample in the corresponding database execution environment; verification information on whether the candidate SQL sample meets the constraints of the corresponding SQL dialect environment; and consistency information on whether the execution result of the candidate SQL sample is consistent with the baseline execution result.

[0020] In one embodiment, based on the execution feedback information, the natural language samples, the baseline SQL samples, and the candidate SQL samples are subjected to sample screening, sample labeling, or sample adjustment to obtain training samples, including: removing candidate SQL samples that fail to execute in the corresponding database execution environment; labeling or adjusting candidate SQL samples that execute successfully but whose execution results are inconsistent with the baseline execution results; and retaining candidate SQL samples that execute successfully and whose execution results are consistent with the baseline execution results as part of the training samples.

[0021] In one embodiment, before obtaining the training samples, the method further includes: constructing auxiliary context information for the natural language samples or the benchmark SQL samples, the auxiliary context information including at least one of the following: database schema summary information; field value information related to the query task; example information related to the query task; experience hints related to the query task; and adding interference information to the auxiliary context information to obtain enhanced training samples in the training samples.

[0022] In one embodiment, adding interference information to the auxiliary context information to obtain enhanced training samples in the training samples includes: adding irrelevant field values ​​to the field value information related to the query task; adding interfering examples to the example information related to the query task; and adding redundant prompt information that does not correspond to the baseline SQL sample to the experience prompt information related to the query task.

[0023] An embodiment of the present invention also provides a training apparatus for a natural language to SQL model, comprising: an environment construction module, configured to acquire a database instance and construct a database execution environment corresponding to at least two SQL dialect environments based on the database instance; a sample generation module, configured to generate a baseline SQL sample corresponding to a query task and a natural language sample semantically corresponding to the baseline SQL sample based on the database instance, and generate candidate SQL samples in the corresponding SQL dialect environments according to the at least two SQL dialect environments; an execution verification module, configured to send the candidate SQL samples to the corresponding database execution environments for execution verification to obtain execution feedback information; a sample processing module, configured to perform sample screening, sample annotation, or sample adjustment on the natural language samples, the baseline SQL samples, and the candidate SQL samples according to the execution feedback information to obtain training samples; and a model optimization module, configured to train the natural language to SQL model using the training samples, and construct training feedback based on the execution feedback information during the training process to update the parameters of the natural language to SQL model.

[0024] An embodiment of the present invention also provides an electronic device, including a processor and a memory, wherein the memory stores a computer program, and when the computer program is executed by the processor, the electronic device performs the above-described training method.

[0025] An embodiment of the present invention also provides a computer-readable storage medium storing a computer program, which, when executed by a processor, causes the processor to perform the above-described training method.

[0026] By adopting the above technical solution, database execution environments corresponding to at least two SQL dialect environments are constructed around the same database instance. Candidate SQL samples are then executed and validated under different SQL dialect environments. This ensures that training samples include database environment constraints and execution result constraints before entering model training, thereby reducing the likelihood of the model relying solely on a single dialect expression for learning. Using execution feedback information for sample selection, annotation, adjustment, and model parameter updates makes the training objective more closely approximate the executability and correctness of the target database environment. Furthermore, by constructing auxiliary context information and incorporating interference, the training process can cover input formats closer to actual deployment conditions, thus improving the executability, result consistency, and stability of the natural language to SQL model under multi-dialect database environments and complex input conditions. Attached Figure Description

[0027] To more clearly illustrate the technical solutions of the embodiments in this specification, the drawings used in the description of the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments recorded in this specification. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0028] Figure 1 This is a flowchart illustrating the overall process of training a natural language to SQL model according to one embodiment of the present invention.

[0029] Figure 2 This is a schematic diagram illustrating the construction of a multi-dialect database execution environment in one embodiment of the present invention.

[0030] Figure 3 This is a schematic diagram illustrating the correspondence between the query task, the baseline SQL sample, the natural language sample, and the candidate SQL sample in one embodiment of the present invention.

[0031] Figure 4 This is a flowchart illustrating the execution verification and execution feedback information generation process in one embodiment of the present invention.

[0032] Figure 5 This is a schematic diagram of the training sample construction and enhancement process in one embodiment of the present invention.

[0033] Figure 6 This is a structural block diagram of a natural language to SQL model training device according to one embodiment of the present invention.

[0034] Figure 7 This is a schematic diagram of the structure of an electronic device according to one embodiment of the present invention.

[0035] Figure 8 This is a schematic diagram illustrating the training feedback construction and model parameter update in one embodiment of the present invention. Detailed Implementation

[0036] To enable those skilled in the art to better understand the technical solutions in this specification, the technical solutions in the embodiments of this specification will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of this specification, and not all embodiments. Based on the embodiments in this specification, all other embodiments obtained by those skilled in the art without creative effort should fall within the scope of protection of this specification.

[0037] The specific embodiments of the present invention will be further described below with reference to the accompanying drawings. Figure 1This document illustrates the overall flow of a natural language to SQL model training method. Step S110 involves obtaining a database instance and constructing database execution environments corresponding to at least two SQL (Structured Query Language) dialect environments based on the database instance. Step S120 involves generating a baseline SQL sample corresponding to a query task, and natural language samples semantically corresponding to the baseline SQL sample, based on the database instance. Step S130 involves generating candidate SQL samples in the corresponding SQL dialect environments based on the at least two SQL dialect environments. Step S140 involves sending the candidate SQL samples to the corresponding database execution environments for execution verification to obtain execution feedback information. Step S150 involves performing sample filtering, labeling, or adjustment on the natural language samples, the baseline SQL samples, and the candidate SQL samples based on the execution feedback information to obtain training samples. Step S160 involves training the natural language to SQL model using the training samples, and constructing training feedback based on the execution feedback information during the training process to update the model parameters. Figure 2 The construction relationship of a multi-dialect database execution environment is illustrated. After the database instance 201 is processed by structure normalization and dialect mapping 202, it can generate table creation statements and data writing statements 203 applicable to different SQL dialect environments, and establish a first SQL dialect execution environment 211 and a second SQL dialect execution environment 212 based on the table creation statements and data writing statements 203. Figure 3 The correspondence between query task, baseline SQL sample, natural language sample and candidate SQL sample is shown. Query task 301 corresponds to baseline SQL sample 302. Baseline SQL sample 302 further corresponds to natural language samples 303 with multiple expression styles and candidate SQL samples 304 corresponding to different SQL dialect environments. Figure 4 The process of execution verification and execution feedback information generation is shown. After the candidate SQL sample 401 is processed by the database execution environment 402, execution status information 403, result set information 404, dialect constraint verification information 405 and consistency information 406 are obtained. Figure 5 The training sample construction and enhancement process is shown. The auxiliary context information 501 includes database pattern summary information 511, field value information 512, example information 513 and experience hint information 514. The interference information injection module 520 writes interference information into the auxiliary context information 501 to form enhanced training samples 530. Figure 6 The functional structure of the training device is shown, including an environment construction module 601, a sample generation module 602, an execution verification module 603, a sample processing module 604, and a model optimization module 605. Figure 7 The hardware structure of the electronic device is shown, with processor 701, memory 702, communication interface 703 and bus 704 interconnected. Figure 8 The relationship between training feedback construction and parameter update is shown. Training sample 801 is input into the natural language to SQL model 802, the model outputs SQL candidates 803, execution feedback 804 participates in training feedback construction 805, and drives parameter update 806.

[0038] In step S110, a database instance can be selected from a pre-organized database set, or it can be automatically constructed based on existing database samples. The database instance 201 is not limited to a simple set of table creation statements, but can include table structure information, field type information, primary key relationships, foreign key relationships, sample data, and field value distribution information. Retaining the field value distribution information is beneficial for subsequently constructing natural language samples 303 around the query task, and also helps identify candidate SQL samples 401 that are semantically unreasonable but syntactically executable during the execution verification phase. If the database instance 201 only contains table structure and not data content, partial syntax verification can be completed, but it is difficult to further judge the consistency of the results. Therefore, in this embodiment, it is preferable to retain structured data content.

[0039] Step S110 includes not only obtaining database instance 201, but also... Figure 2 The diagram illustrates the construction of a multi-dialect database execution environment. This database execution environment is not simply data replication, but rather the creation of multiple dialect environments, each capable of actually executing SQL statements, around the same database instance 201. Figure 2 For example, database instance 201 first enters structure normalization and dialect mapping 202. Structure normalization and dialect mapping 202 can be used to convert the tables, fields, constraints, and data types in the original database instance into a unified intermediate semantic representation, and then generate an adaptation result according to the requirements of the target SQL dialect environment. Subsequently, table creation statements and data writing statements 203 suitable for different SQL dialect environments can be formed, and a first SQL dialect execution environment 211 and a second SQL dialect execution environment 212 are established in the corresponding database system, respectively.

[0040] Structure normalization and dialect mapping 202 play a crucial role in this process. Directly copying the original database instance 201 often leads to implicit differences between different database execution environments. For example, time fields, boolean fields, or string fields may be defined differently in different database systems. Ultimately, the execution differences in subsequent candidate SQL samples 304 do not stem entirely from the SQL dialect itself, but rather from environment construction errors. Through structure normalization and dialect mapping 202, intermediate representations such as table sets, field sets, field attribute sets, and relation constraint sets can be extracted and then mapped to the syntactic structures of the first SQL dialect execution environment 211 and the second SQL dialect execution environment 212, respectively. This ensures that the multiple database execution environments constructed in this way maintain consistency at the database semantic level, with differences mainly reflected in the syntax and execution constraints corresponding to the target SQL dialect environment.

[0041] Table creation statements and data write statements 203 can be generated separately according to different SQL dialect environments. In one embodiment, if time semantic fields, numeric semantic fields, and enumeration semantic fields exist in database instance 201, then structure normalization and dialect mapping 202 can first identify the unified semantics of these fields, and then generate corresponding data definition statements and data write statements for different SQL dialect environments. For example, an order time field can be defined using one time type in the first SQL dialect execution environment 211, and another time type in the second SQL dialect execution environment 212. Similarly, a Boolean status field can be used as a Boolean type in one database system, and mapped to an integer or character type in another. By performing pre-mapping on these differences, the candidate SQL samples 304 subsequently generated around the same query task 301 have a comparable execution basis.

[0042] In a specific scenario, database instance 201 may include an order table, a user table, and a product table. The order table may contain an order time field and an order status field, the user table may contain a registration city field, and the product table may contain a category field. If the original table structure is directly copied to the two database systems, the execution results of the same query logic may deviate due to differences in the target databases' support for date functions, default value expressions, or null value rules. After processing through structure normalization and dialect mapping 202, the order time field can be identified as a unified time semantic field, and then table creation statements and data writing statements 203 adapted to the first SQL dialect execution environment 211 and the second SQL dialect execution environment 212 can be generated respectively. The two database execution environments established based on these statements can provide a consistent semantic basis for the parallel verification of the same query task 301 in the future.

[0043] After step S110 is completed, step S120 can be proceeded. Step S120 generates a baseline SQL sample 302 and a natural language sample 303 based on query task 301. Query task 301 here is not equivalent to a simple natural language question, but rather a task description that falls within the semantics of database retrieval. Query task 301 can include at least one of the following: target data object, filtering conditions, aggregation method, sorting conditions, and time range. For example, counting the number of users placing orders each month in 2024, querying the top ten merchants by transaction amount in the last 30 days, and filtering order records from a specified region with a completed order status can all be considered query task 301. In this solution, query task 301 is equivalent to a semantic skeleton. Both the baseline SQL sample 302 and the natural language sample 303 are constructed around this semantic skeleton, rather than being generated separately and then weakly matched.

[0044] Figure 3 The baseline SQL sample 302 is used to represent the standardized query logic of query task 301. The term "baseline SQL sample 302" is used instead of the final training SQL because this sample is more semantic and structurally based. Baseline SQL sample 302 is used to determine the core retrieval logic of query task 301, such as which tables, fields, join conditions, filtering relationships, aggregation methods, and output columns are involved. Baseline SQL sample 302 can be represented directly using a neutral representation or a stable representation under a preset dialect. If the latter is used, the adaptation to other SQL dialect environments in step S130 can be carried out around this baseline.

[0045] The baseline SQL sample 302 can be manually constructed or automatically generated. When automatically generated, baseline SQL samples 302 of different difficulty levels can be constructed based on the schema information and data distribution in database instance 201, according to preset complexity rules. Simple-level samples typically correspond to single-table queries, basic filtering, simple sorting, and limiting the number of rows returned. Medium-level samples typically introduce aggregation, grouping, and multi-table joins. Complex-level samples can involve nested subqueries, window functions, common table expressions, and conditional branches. The complexity rules are not only used to expand the sample types but also to allow the training system to observe differences in cross-dialect expressions at different complexity levels.

[0046] In one embodiment, the complexity score of any benchmark SQL sample 302 can be determined by a weighted sum of various structural features:

[0047] (1)

[0048] In the formula, This represents the complexity score of the benchmark SQL sample 302. Indicates the number of join operations. Indicates the number of aggregation operations. Indicates the number of subqueries. Indicates the number of window functions. Indicates the number of common table expressions. to This represents the weighting coefficient of the corresponding structural feature. The weighting coefficient can be preset or determined based on historical sample statistics. When the complexity score reaches different intervals, the corresponding benchmark SQL sample 302 can be classified into simple, medium, or complex levels respectively. Using this method, complexity rules can be transformed into executable sample organization standards, rather than relying solely on rough classifications based on human experience.

[0049] Based on the baseline SQL sample 302, a corresponding natural language sample 303 can also be generated. The natural language sample 303 can have different expression styles, but its core semantics should remain consistent with the baseline SQL sample 302. For example, if the baseline SQL sample 302 represents counting the number of users who placed orders in 2024 by month, then the natural language sample 303 can be expressed as counting the number of users who placed orders each month in 2024, checking how many users placed orders each month in 2024, or viewing the number of users who placed orders in 2024 by month, etc. Preserving differences in expression styles helps the natural language to SQL model 802 maintain its ability to map the same query intent under different expression methods. If certain rewrites cause semantic shifts, such as mistakenly writing the number of users who placed orders as the number of orders, then this type of natural language sample 303 is not suitable for subsequent processes. Therefore, the generation of the natural language sample 303 should be within the semantic boundaries of the baseline SQL sample 302.

[0050] In one embodiment, natural language samples 303 can be generated through template replacement, synonym conversion, sentence restructuring, and omission rewriting. Template replacement is suitable for statistical problems with relatively stable structures; synonym conversion is suitable for mapping between field names and common business terms; sentence restructuring is suitable for generating interrogative, imperative, and descriptive expressions; and omission rewriting is suitable for simulating incomplete but still understandable input methods in real-world scenarios. For the same baseline SQL sample 302, the number of natural language samples 303 can be one or more. If a large number of samples are generated, excessively repetitive expressions can be removed by setting a similarity threshold to avoid overly concentrated distribution of training samples.

[0051] Step S130 Acceptance Figure 3 The baseline SQL sample 302 and query task 301 are used to generate candidate SQL samples 304 in the corresponding SQL dialect environment based on at least two SQL dialect environments. Figure 3Candidate SQL sample 304 is not automatically generated after the baseline SQL sample 302 is generated; rather, it needs to be constructed separately for the target SQL dialect environment. The key technical aspect of this process is that the same query task 301 typically cannot directly reuse the same SQL text expression in different database execution environments. Candidate SQL sample 304 must maintain query semantics consistent with the baseline SQL sample 302 while also satisfying the syntactic requirements and execution constraints of the corresponding SQL dialect environment. If only semantic consistency is maintained while dialect adaptation is ignored, candidate SQL sample 304 may report an error in the target database execution environment 402; if only syntactic requirements are satisfied while semantic consistency is ignored, although it can be executed, the result may deviate from query task 301.

[0052] In one embodiment, step S130 can use a rule-based mapping approach to handle cross-dialect differences. For parts with clearly defined differences, such as basic functions, date expressions, string concatenation, null value handling, pagination, and type conversion, a mapping relationship can be established from the baseline SQL sample 302 to the target SQL dialect expression. For example, when the baseline SQL sample 302 contains expressions such as date truncation, null value replacement, or pagination restrictions, the candidate SQL sample 304 can use different function syntax, keyword syntax, or clause organization methods in the first SQL dialect execution environment 211 and the second SQL dialect execution environment 212. By decomposing dialect differences into a maintainable set of mapping rules, the candidate SQL sample 304 can be adapted around the same semantic skeleton, rather than being completely regenerated in each dialect environment.

[0053] When the query structure is complex, relying solely on string-level replacement is often insufficient to maintain query stability. Therefore, in one embodiment, step S130 may first perform structural analysis on the baseline SQL sample 302, and then generate candidate SQL samples 304 based on the structural analysis results. The objects of structural analysis may include query blocks, join relationships, filtering conditions, aggregation structures, sorting conditions, and output columns. For each type of structural element, mapping rules for the target SQL dialect environment can be established separately, and then the specific expression can be replaced while preserving the structural hierarchy. For example, in scenarios involving nested queries, window functions, or common table expressions, direct string replacement can easily lead to situations where local replacements are possible but the overall structure is mismatched; performing structural analysis first and then generating candidate SQL samples 304 is more conducive to controlling equivalent expressions under different dialects.

[0054] In one embodiment, the generation of candidate SQL sample 304 can rely on an abstract grammatical representation. The baseline SQL sample 302 can first be parsed into an abstract grammatical structure, which preserves table references, field references, conditional expressions, collation rules, and aggregation relationships. Subsequently, the abstract grammatical structure is re-linearized according to the target SQL dialect environment to obtain the corresponding candidate SQL sample 304. This approach reduces semantic drift during dialect adaptation of complex samples, and is particularly suitable for scenarios with multiple table joins, grouping aggregations, and multiple subquery levels. If subsequent expansion to a third or more SQL dialect environments is required, this abstract grammatical structure can be reused without reverting to rewriting the original SQL text.

[0055] In a specific example, if query task 301 is to count the number of users who place orders each month in 2024, the baseline SQL sample 302 can be represented as a query logic that groups users by month based on the order time field and performs deduplication on user identifiers. For the first SQL dialect execution environment 211, the month extraction function and grouping expression supported by the corresponding environment can be used; for the second SQL dialect execution environment 212, another set of date functions and type processing expressions can be used. Although the two candidate SQL samples 304 may differ in text form, they are still constructed around the same query task 301 and the same baseline SQL sample 302. In this way, when the subsequent step S140 performs verification, if there is a difference in the execution results obtained by the two samples, it is easier to determine whether the difference comes from the correctness of dialect adaptation, rather than from the fact that the query semantics themselves have shifted.

[0056] Step S130 differs from allowing the model to generate SQL freely. While direct generation is flexible, it introduces more sources of error during the training sample construction phase. If candidate SQL sample 304 relies entirely on free text generation, it becomes difficult to distinguish whether subsequent execution failures stem from dialect incompatibility, semantic shifts, or generation errors. By adopting a dialect-adapted generation method based on the baseline SQL sample 302, the correspondence between candidate SQL sample 304 and query task 301 becomes more stable, providing a comparable basis for execution verification in step S140.

[0057] Step S140 accepts candidate SQL sample 304 and Figure 4 The database execution environment 402 shown is used to perform execution verification on the candidate SQL sample 401 and generate execution feedback information. Figure 4The execution feedback information is not a single success or failure marker, but can contain multiple types of feedback content. In one embodiment, the execution feedback information includes at least execution status information 403 and execution result information (equivalent to result set information) 404, and may also include dialect constraint verification information 405 and consistency information 406. The execution verification process can be completed by the execution verification module 603, or the database execution environment 402 can first return the original result, and then the upper-level processing logic can generate a more structured feedback record.

[0058] Execution status information 403 describes the executable status of candidate SQL sample 401 in the current database execution environment 402. Executability status can include execution success, syntax error, missing object, type mismatch, timeout termination, and resource-constrained termination. Syntax errors often mean that candidate SQL sample 401 does not meet the syntax rules corresponding to the target SQL dialect environment; missing objects usually indicate that candidate SQL sample 401 references a table, field, or alias that does not exist in the current database instance 201; type mismatch is often related to differences in explicit or implicit type conversions across dialect environments. While timeout termination and resource-constrained termination do not necessarily indicate semantic errors, they usually indicate that the sample has poor stability as a standard training sample in the current training phase, and therefore can be identified separately during subsequent sample processing.

[0059] The execution result information 404 describes the result returned when candidate SQL sample 401 is executed successfully. This result can be a complete result set or a structured representation of the result set, such as a set of result columns, the number of records, key field values, statistics, or a result summary. Whether to retain the complete result set depends on the resource constraints of the training system. If the database instance 201 is small and the total number of samples is controllable, retaining the complete result set is more beneficial for fine-grained consistency judgment. If the sample size is large, directly saving the complete result set will incur storage and comparison overhead. In this case, result summaries such as the number of rows, column sequences, key column statistics, or sorted hash values ​​can be retained. As long as these summaries can stably reflect the core characteristics of the execution result, they can still be used for subsequent consistency comparisons.

[0060] Dialect constraint verification information 405 indicates whether candidate SQL sample 401 conforms to the syntax and expression rules of the current SQL dialect environment. This information is related to execution status information 403, but not entirely equivalent. Some candidate SQL samples 401 can be executed successfully in the current database execution environment 402, but may rely on compatibility syntax, non-recommended function syntax, or version-sensitive expressions. Although such samples are temporarily usable in the current environment, they may fail when the environment version changes or deployment differences occur. By extracting these cases separately as dialect constraint verification information 405, more stable expressions can be preserved in training samples. For example, a candidate SQL sample 401 can be compatiblely parsed in the first SQL dialect execution environment 211, but its function call form does not conform to the preset dialect specification. In this case, execution status information 403 can still be marked as successful, while dialect constraint verification information 405 can be marked as not meeting the preset constraints.

[0061] Consistency information 406 describes whether the execution result of candidate SQL sample 401 is consistent with the baseline execution result. The baseline execution result should stably represent the target result of query task 301, without being confined to a single SQL text form. In one embodiment, the baseline execution result can be obtained by executing baseline SQL sample 302 in a preset baseline environment, or it can be directly provided by a standard result generation module that has undergone manual verification. Using the former method requires ensuring high reliability of the baseline SQL sample 302 and its execution environment; using the latter method is more suitable for scenarios with a high proportion of important samples or manually annotated samples. The role of consistency information 406 is to transform text alignment into result alignment. Even if the text form of a candidate SQL sample 401 differs significantly from that of the baseline SQL sample 302, as long as its execution result is consistent with the baseline execution result, its semantics can still be considered valid.

[0062] In one embodiment, consistency information 406 can be determined through a result comparison function. If the complete result set is retained, the candidate result set can be directly compared with the baseline result set for similarity. If only the result summary is retained, consistency can be determined based on a combination of multiple summary items. To accommodate differences in column order, irrelevant formatting, and equivalent representation, the result comparison process can employ standardization. Let the standardized representation of the candidate result set be... The standardized representation of the benchmark result set is as follows Then the consistency score It can be represented as:

[0063] (2)

[0064] In the formula, This represents the consistency score between the candidate result and the benchmark result. This indicates the number of standardized result elements in the intersection of the two. This represents the number of standardized result elements in the union of the two sets. These standardized result elements can be complete records or summary units that have undergone primary key sorting, numerical normalization, and string normalization. When the consistency score... When the preset threshold is reached, candidate SQL sample 401 can be determined to be consistent with the benchmark execution result; when the consistency score is lower than the threshold, candidate SQL sample 401 can be considered to have semantic deviation. If the execution result itself is a single-value statistic, numerical equality or error range can also be directly compared.

[0065] In one embodiment, step S140 does not require immediate decision-making after processing each candidate SQL sample 401 independently. A more robust approach is to create an execution record for each query task 301. This execution record may include a query task identifier, a baseline SQL sample identifier, a candidate SQL sample identifier, a target dialect environment identifier, execution time, execution status information 403, execution result information 404, dialect constraint verification information 405, and consistency information 406. This recording method allows for aggregation analysis by query task dimension or by dialect environment dimension in subsequent step S150. For example, for the same query task 301, the execution stability of different candidate SQL samples 401 in different dialect environments can be compared, thereby distinguishing between dialect adaptation issues and semantic deviation issues.

[0066] In a specific scenario, if query task 301 is to count the number of users placing orders each month in 2024, then candidate SQL sample 401 under the first SQL dialect execution environment 211 may execute correctly and return the expected result; although candidate SQL sample 401 under the second SQL dialect execution environment 212 executes successfully, due to improper expression of month extraction, some dates are incorrectly merged. At this time, the execution status information 403 may both be successful, but the execution result information 404 is different, and the consistency information 406 will also show significant differences. Through this multi-dimensional feedback structure, step S140 can not only identify grammatical error samples, but also semantic deviation samples and dialect compatibility boundary samples, providing a more sufficient basis for subsequent sample screening, labeling, and adjustment.

[0067] Step S150 follows the execution feedback information returned in step S140 and is used to perform sample screening, sample labeling, or sample adjustment on the natural language sample 303, the benchmark SQL sample 302, and the candidate SQL sample 401 to form training samples that can be used for training. Figure 4In this embodiment, the execution feedback information is not supplementary information, but rather a core basis for training sample quality control. If the training process determines sample usability solely based on whether an SQL text is generated, the model is prone to learning expressions that are formally close to the reference answer but unstable in a real database execution environment. By incorporating execution status information 403, execution result information 404, dialect constraint verification information 405, and consistency information 406 into the sample processing logic, the retention and correction of training samples can be based on real execution results.

[0068] In one embodiment, step S150 may include sample screening. Sample screening is used to determine whether a candidate SQL sample 401 should be directly included in the training set. Candidate SQL samples 401 that exhibit syntax errors, missing objects, or type errors in the database execution environment 402 and cannot be automatically corrected are generally not suitable for direct inclusion in the training set. If such samples are retained indiscriminately, the model may learn incorrect dialect expressions, field referencing methods, or function usage methods. For samples that time out, further judgment can be made based on the complexity of the query task 301, the size of the database instance 201, and the reason for the timeout. If the timeout is mainly due to environmental anomalies or temporary resource fluctuations, it can be retried; if the timeout is mainly due to the SQL structure itself being clearly unreasonable, it can be removed. For samples that execute successfully but have low consistency information 406, whether to remove them directly can be determined based on the training objective. If only positive samples are constructed during the training phase, they can be removed; if the training process allows for the introduction of mislabeled samples or difficult samples, they can also be retained in another sample set.

[0069] Step S150 may further include sample labeling processing. Sample labeling processing is used to transform execution feedback information into labels usable for training. Labels may include at least one of the following: executable label, result consistency label, dialect adaptation label, error type label, and sample confidence label. The executable label indicates whether the candidate SQL sample 401 can be successfully executed in the corresponding database execution environment 402. The result consistency label indicates whether its execution result is consistent with the baseline execution result. The dialect adaptation label describes whether the candidate SQL sample 401 satisfies the syntax and expression constraints corresponding to the current SQL dialect environment. The error type label can be further subdivided into syntax errors, object errors, type errors, logical errors, timeout errors, etc. The sample confidence label can be generated by combining execution status, consistency degree, and dialect constraint satisfaction degree, and can be used to adjust sample weights during subsequent training.

[0070] In one embodiment, the sample confidence score It can be determined in the following way:

[0071] (3)

[0072] In the formula, This indicates the sample credibility score. This represents the execution status score, with a higher value for successful execution and a lower value for failed execution. The consistency score obtained from expression (2) is shown. This represents the dialect constraint score, with the higher value taken when candidate SQL sample 401 satisfies the corresponding SQL dialect environment constraint. , and This represents the corresponding weight coefficient. Using this score, step S150 can divide the candidate SQL samples 401 into high-confidence samples, medium-confidence samples, and low-confidence samples. High-confidence samples can be directly incorporated into the training set, medium-confidence samples can be used after further refinement, and low-confidence samples can be removed or transferred to the error sample set. This hierarchical approach helps to dynamically adjust the training intensity based on sample quality during the training phase, rather than treating all samples equally.

[0073] Step S150 may also include sample adjustment processing. Sample adjustment processing differs from simple deletion; its goal is to correct a portion of the candidate SQL samples 401 that are close to the correct boundary into usable samples. If execution status information 403 indicates an object name mismatch, the field mapping information in database instance 201 can be traced back to determine if there are synonymous fields, field aliases, or table aliases errors. If dialect constraint verification information 405 indicates that the function syntax does not conform to the target SQL dialect environment, the dialect mapping rules used in step S130 can be invoked to perform local replacements on the corresponding SQL fragments. If consistency information 406 indicates that the result deviation is small and mainly concentrated in sorting direction, null value handling, or type conversion, targeted corrections can also be made around these local fragments. The corrected candidate SQL samples 401 can be resubmitted. Figure 4 The verification process is executed as shown. In this way, some samples that would otherwise be discarded can be transformed into more stable training samples, thereby improving sample utilization.

[0074] In one embodiment, the training samples formed in step S150 may include not only natural language samples 303 and candidate SQL samples 401 and their labels, but also a baseline SQL sample 302 and an execution feedback summary. This organization of training samples has two advantages. First, subsequent training phases can utilize both the natural language-to-SQL mapping and the execution feedback-driven model to learn why one candidate SQL sample 401 is acceptable while another is unacceptable. Second, if the training method incorporates execution feedback-driven parameter updates, it is not necessary to backtrack the original database execution logs during each training iteration; the feedback summary retained in the training samples can be used directly. For large-scale sample databases, this pre-organization helps reduce the dependence of the training phase on the online database environment.

[0075] In a specific example, if query task 301 is to count the number of users placing orders each month in 2024, then candidate SQL sample 401 under the first SQL dialect execution environment 211 may execute correctly and be consistent with the baseline execution result. Although candidate SQL sample 401 under the second SQL dialect execution environment 212 executes successfully, due to a deviation in the date truncation expression, the monthly merge result is incorrect, resulting in a decrease in the consistency score. After receiving these two types of feedback, step S150 can directly retain the first candidate SQL sample 401 and mark the second candidate SQL sample 401 as an inconsistent result sample, or perform a partial replacement based on the dialect mapping rules of the date field and re-execute the verification. The training samples obtained in this way not only distinguish between correct and incorrect results but also retain the location and nature of the errors, facilitating subsequent model learning of more stable generation paths under different SQL dialect environments.

[0076] After the basic training samples are formed in step S150, the training process does not end. If the training samples only contain natural language samples 303 and candidate SQL samples 401, the model may still become unstable when encountering interfering auxiliary contexts in the deployment scenario. Therefore, in one embodiment, step S150 can also be combined with... Figure 5 The training sample construction and enhancement process shown is combined. Figure 5 The auxiliary context information 501 is used to incorporate environmental factors outside of the query task 301 into the training input. The auxiliary context information 501 may include database schema summary information 511, field value information 512, example information 513, and experience hint information 514. The perturbation information injection module 520 can add controlled perturbations to the auxiliary context information 501 to form enhanced training samples 530.

[0077] The database schema summary information 511 describes the tables, fields, and their relationships related to the current query task 301. This information can be extracted from the database instance 201, or it can be converted into a textual summary after generating a core schema subgraph based on the tables and fields involved in the baseline SQL sample 302. For example, when the baseline SQL sample 302 involves an order table and a user table, the database schema summary information 511 can retain the order time, user ID, and transaction amount fields from the order table, the user ID and registration city fields from the user table, and the relationship between the two tables through the user ID. The schema summary formed in this way is more compact than directly inputting the complete database schema and is easier to correspond to the current query task 301.

[0078] Field value information 512 is primarily used to supplement value range clues related to query task 301. Natural language samples 303 frequently contain conditions such as region names, status names, product categories, and time ranges, which may not perfectly match the standard values ​​in the database. Field value information 512 can provide representative values ​​related to the order status field, or typical region names related to the region field. Field value information 512 can be directly sampled from database instance 201, or it can be selectively extracted from relevant fields related to the current query task 301. The latter approach is more suitable for this solution because it has a stronger constraint relationship with the current query task 301, which is more conducive to subsequent field mapping and condition value matching in the model.

[0079] Example information 513 is used to provide query examples similar to the current query task 301. These examples are not required to be completely identical to the current natural language sample 303, but rather to have a certain degree of similarity in table structure, query logic, or expression. If the current query task 301 involves counting the number of users placing orders by month, example information 513 can select samples from the same database instance that count the number of orders by month, or count sales by quarter, etc. If the example similarity is too high, the model may directly copy the SQL structure in the example; if the similarity is too low, its reference value is limited. Therefore, the selection range of candidate examples can be controlled based on their similarity to the current query task 301, ensuring that the examples are relevant without replacing the model's true understanding of the current task.

[0080] The experience-based hints 514 typically originate from stable rules or common correction experiences accumulated during historical training, rather than directly from the database instance 201. For example, the experience-based hints 514 might include which type of date extraction representation to prioritize in monthly statistics, which foreign key relationships to prioritize in multi-table joins, and what functional differences to pay attention to when handling null values. This information helps to explicitly inject frequently encountered issues discovered during training into the input context, thereby enhancing the model's awareness of constraints in specific SQL dialect environments or query structures. To avoid the model over-relying on the experience-based hints 514, summary hints can usually be used instead of covering the entire rule set.

[0081] In one embodiment, the auxiliary context information 501 can be generated either statically or through online retrieval. Vectorized indexes can be established for example information 513, field value information 512, and experience hint information 514, respectively. For the current query task 301 or natural language sample 303, a query vector can be generated, and a similarity retrieval can be performed in the vectorized index based on the query vector to recall auxiliary context content related to the current task. Example information 513 can be recalled as a few-sample example, field value information 512 can be recalled as cell value information related to the current query task, and experience hint information 514 can be recalled as experience rules. Using this approach, the auxiliary context information 501 is no longer a statically stacked external information, but rather a dynamically filtered set of context information surrounding the current query task 301, thus enabling closer integration with the generation and correction process of candidate SQL samples 304.

[0082] After the auxiliary context information 501 is constructed, Figure 5 The interference information injection module 520 can add interference information. This interference information does not arbitrarily disrupt the input, but rather provides controlled perturbation to the auxiliary context layer while maintaining the semantic correspondence between the natural language sample 303 and the baseline SQL sample 302, and the basic semantics of the database instance 201. The purpose of this design is to make the enhanced training sample 530 more closely resemble the input state in a real deployment scenario. When the model faces the interference-laden auxiliary context during the training phase, it still needs to return to the query task 301, the database schema, and the execution feedback itself to determine which information should be adopted and which should be suppressed.

[0083] In one embodiment, Figure 5The interference information injection module 520 can employ multiple noise injection methods to create enhanced training samples 530 that more closely resemble real-world usage environments. The first type is example noise. Example noise can be randomly added to the example information 513, including examples unrelated to the current query task 301. These unrelated examples can correspond to other query tasks in the current database instance 201 or come from historical examples in other database instances, but their semantics do not correspond to the current natural language sample 303. To avoid insufficient example noise that fails to create interference or excessive noise that obscures real examples, 2 to 5 completely unrelated examples can be randomly added to a specific example. After this processing, the model cannot generate SQL solely based on the most superficially similar structure in the examples, but needs to comprehensively judge the credibility of the examples by combining the query task 301, the database schema summary information 511, and the execution feedback information.

[0084] The second type is cell noise. Cell noise can be added to the field value information 512 with cell data unrelated to the current query task 301. This unrelated cell data can come from other fields in the current database instance 201, or from non-target value ranges of the current field. For example, adding irrelevant region names in a region-based search scenario, or adding status values ​​inconsistent with the current filter conditions in an order status filtering scenario. In this way, the field value information 512 is no longer a single, pure condition suggestion, but is closer to the set of candidate values ​​that may appear in the real system. During training, the model needs to filter the field value information 512 by combining the constraint semantics and pattern relationships in the natural language samples 303, rather than directly using field values ​​that appear early or have high frequency.

[0085] The third category is empirical noise. Empirical noise can add rule-based hints that conflict with the current database dialect environment or the current SQL logic to the empirical hint information 514. For example, it can add function usage rules from another SQL dialect environment to the current SQL dialect environment, or add misleading summation and aggregation rules when the current query task 301 only needs to perform counting statistics. Empirical noise differs from ordinary redundant hints in that it has a certain rule-like appearance, but it is inconsistent with the target dialect constraints or query logic. If the model relies too much on a single rule in the empirical hint information 514, it is easy to generate candidate SQL samples 304 that do not match the target environment or are inconsistent with the query semantics. After introducing empirical noise into the training samples, the execution feedback information returned in step S140 can be used to suppress the model's erroneous adoption of conflicting rules.

[0086] In one embodiment, the interference injection module 520 can dynamically control the noise injection ratio based on sample complexity, auxiliary context length, and the current training stage. If the interference applied to the simple query task 301 is too weak, the enhanced training sample 530 will not differ significantly from the original training sample, making it difficult to effectively improve the model's robustness. If the interference applied to the complex query task 301 is too strong, it may mask the true task semantics, causing excessive fluctuations in the training process. Therefore, a perturbation ratio can be set for each training sample. Let the number of true context items in the auxiliary context information 501 be... The number of interfering context terms is Then the disturbance ratio It can be represented as:

[0087] (4)

[0088] In the formula, This indicates the proportion of perturbation information in the auxiliary context. For simpler query tasks 301, the perturbation ratio can be appropriately increased to enhance the model's sensitivity to noise; for complex query tasks 301, the perturbation ratio can be appropriately decreased to avoid excessive interference to the model before a stable mapping is formed. In this way, the training samples 530 are enhanced to both preserve the original query semantics and introduce sufficient noise to train the model's robustness.

[0089] Figure 5 The augmented training samples 530 can be used in combination with regular training samples or in batches according to training stages. In one embodiment, clean samples and low-perturbation samples can be used to establish a basic mapping from natural language to SQL in the early stages of training; once the model has a preliminary mapping capability, the proportion of augmented training samples 530 can be gradually increased. This arrangement helps to avoid excessive fluctuations caused by the model simultaneously facing dialect differences, execution feedback differences, and contextual noise in the early stages of training. For complex samples that already have high dialect differences, the perturbation ratio can be further reduced to prevent the same batch of samples from carrying too many uncertainties at the same time.

[0090] Step S160 follows the training samples formed in step S150 and Figure 5 The enhanced training samples 530 are used to train the natural language to SQL model 802, and training feedback is constructed based on execution feedback information to update the model parameters during the training process. Figure 8This illustrates the core relationships in this process. After training sample 801 is input into the natural language to SQL model 802, the model outputs SQL candidates 803, execution feedback 804 participates in the construction of training feedback 805, and drives parameter updates 806. Compared with training methods that rely solely on reference SQL text for supervision, this scheme explicitly introduces execution feedback 804 during the training phase, making parameter updates 806 more closely resemble the behavioral constraints in a real database execution environment.

[0091] In one embodiment, the natural language to SQL model 802 is not limited to a specific network structure. Any model structure capable of processing natural language input, database-related input, and generating SQL output can be used. For example, a sequence generation structure, an encoding / decoding structure, a code generation structure, or a large-model-based generation structure can be employed. The input received by model 802 can include natural language samples 303, auxiliary context information 501, and database environment identifiers. The output SQL candidate 803 can be a complete SQL statement or an intermediate result generated step-by-step. Since the focus of this solution is on the training process rather than a specific model structure, model 802 can be implemented using commonly used generative frameworks in the art.

[0092] In one embodiment, Figure 8 The training feedback construction 805 can transform the execution feedback 804 into a training signal that can participate in parameter updates 806. This training signal can be constructed using either a continuous scoring method or a segmented reward method. If the training process still only compares the lexical differences between the model's output SQL candidate 803 and a certain reference SQL text, the value of the aforementioned multi-dialect execution verification link cannot be fully realized. In real-world scenarios, it often happens that the model's output SQL candidate 803 differs from the baseline SQL sample 302 text, but still yields the correct result in the target database execution environment. If only textual differences are penalized, such semantically correct equivalent expressions will be misjudged. By introducing the execution feedback 804 into the training feedback construction 805, the parameter updates 806 can be made more focused on real execution behavior rather than single text similarity.

[0093] In one embodiment, the training feedback value It can be composed of execution status score, consistency score, and dialect constraint score:

[0094] (5)

[0095] In the formula, This represents the training feedback value. This represents the execution status score of the model output SQL candidate 803 in the target database execution environment. This indicates the consistency score between the model's output SQL candidate 803 and the baseline execution result. This indicates the degree to which it satisfies the constraints of the target SQL dialect environment. , and This represents the corresponding weight coefficient. The training feedback value is given when the model outputs a SQL candidate 803 that executes successfully, yields consistent results, and satisfies dialect constraints. Higher values ​​can be selected; when one of the values ​​is too low, the training feedback value will be lower. The corresponding decrease. Parameter updates (806) can be based on training feedback values. Adjust the model parameters so that the model gradually tends to generate SQL expressions that are executable and semantically correct in a real database execution environment.

[0096] In one embodiment, the training feedback construction 805 can use a segmented reward method to transform the execution feedback 804 into a parameter update signal. For the model output SQL candidate 803, if it executes successfully in the target database execution environment 402 and the execution result is consistent with the benchmark execution result, a higher reward value is assigned; if it can be executed in the target database execution environment 402 and the syntax structure meets the requirements of the current SQL dialect environment, but the execution result is inconsistent with the benchmark execution result, a secondary reward lower than the aforementioned reward value is assigned; if it has a syntax error, an object reference error, or cannot be executed in the target database execution environment 402, a lower reward value is assigned. In a specific example, the reward value can be 1 when the execution is successful and the result is correct, 0.1 when the execution result is incorrect but the syntax is correct, and 0 when neither the syntax nor the result meets the requirements. Through this segmented method, the training feedback construction 805 can distinguish between completely correct, partially correct, and obviously incorrect output paths, so that the parameter update 806 no longer depends solely on the binary signal of correctness.

[0097] In one embodiment, the model optimization module 605 can update the model parameters using the aforementioned reward values ​​through a group-relative strategy optimization. Specifically, multiple model output SQL candidates 803 can be generated for the same natural language sample 303 or the same query task 301, and sent to the target database execution environment 402 for execution verification. Subsequently, a relative merit-discrimination relationship is constructed within the same group of samples based on the reward values ​​corresponding to each candidate SQL, so that candidate SQLs with higher reward values ​​receive higher weights in parameter update 806, while candidate SQLs with lower reward values ​​are suppressed in parameter update 806. This approach helps reduce the limitations on equivalent representations when relying solely on a single reference SQL text for supervision, while accelerating the model learning of generation paths with high executability and result consistency in the real database execution environment.

[0098] In one embodiment, the segmented reward method can also be used in conjunction with consistency scores and dialect constraint scores. If a model outputs SQL candidate 803, executes successfully, and the result is correct, but it uses an unstable compatibility expression, its base reward value can still remain high, while being appropriately adjusted based on the dialect constraint score. If a model outputs SQL candidate 803, which is syntactically correct but only partially matches the result, its reward value can be refined by combining the consistency score with the secondary reward. This training feedback retains both the simplicity of implementing discrete rewards and the ability to distinguish complex differences in execution results, making it more suitable for... Figure 8 The training feedback construction 805 and parameter update 806 processes shown are used together.

[0099] In one embodiment, parameter updates 806 do not need to re-access the database execution environment in each training iteration. Execution feedback 804 can be divided into two parts. One part is the offline feedback summary generated and stored in the training samples during the sample preprocessing stage, used for regular training batches; the other part is the immediate feedback obtained during specific training rounds or for difficult samples, used to supplement stronger timeliness constraints. Training feedback construction 805 can comprehensively utilize these two parts of execution feedback 804 to achieve a balance between training cost and feedback quality. If all feedback is offline, the model's adaptation speed to its latest output path may be slightly slower; if all feedback is online, the training overhead will increase significantly. Therefore, using a primarily offline approach supplemented by online feedback is more suitable for large-scale training scenarios.

[0100] As step S160 continues, the natural language to SQL model 802 gradually develops expression preferences for different database environments. For example, when faced with the same query task 301, the model no longer simply uses the function call method of a single environment, but selects a candidate SQL structure more suitable for the current environment based on the database environment identifier in the input and the dialect constraints learned during training. If the input also contains enhanced auxiliary context information 501, the model can also rely more on the constraints accumulated from the database schema summary information 511 and execution feedback 804, rather than blindly following the local interference content in the example information 513 or experience hints 514. The resulting model is not only closer to the reference sample in static text, but also closer to the target behavior at the database execution level.

[0101] Let's illustrate with a specific example. Figure 5 and Figure 8The coordination between them is crucial. If the current query task 301 is to query the number of users who placed orders each month in 2024, the auxiliary context information 501 can include a schema summary of the order table and the user table, a representative value of the order status field, and a similar statistical example. The interference information injection module 520 can add irrelevant region names to the field value information 512 and add examples of the number of orders to the example information 513. If the model 802 relies too much on the closest example during training, it may incorrectly convert the target aggregation object from the number of users to the number of orders; if it only relies on the field values ​​that appear most frequently, it may also mistakenly select the filtering conditions. The execution feedback 804 can play a corrective role at this time. If the model outputs the SQL candidate 803 and obtains an incorrect result due to the wrong aggregation field selection, the consistency score will decrease, the training feedback value will decrease, and the parameter update 806 will suppress this erroneous path. After multiple rounds of training, the model will be more inclined to determine the aggregation object based on the query task 301 itself and the schema relationship, rather than being biased by local noise.

[0102] Combination Figures 1 to 8 The training process in this embodiment can be understood as a multi-dialect parallel training chain revolving around the same database instance 201. In this chain, Figure 1 Step S110 is used to complete the acquisition of the database instance and the construction of the multi-dialect database execution environment. Figure 2 The relationship between structure normalization and dialect mapping 202, table creation statements and data writing statements 203, and the first SQL dialect execution environment 211 and the second SQL dialect execution environment 212 in this construction process is elaborated. Step S120 forms a baseline SQL sample 302 and a natural language sample 303 around the query task 301. Figure 3 The document further provides the correspondence between query task 301, baseline SQL sample 302, natural language sample 303, and candidate SQL sample 304. Steps S130 and S140 correspond to the generation and execution verification process of candidate SQL sample 304 in different dialect environments, respectively. Figure 4 The execution feedback information, including execution status information 403, result set information 404, dialect constraint verification information 405, and consistency information 406, is presented in a structured manner. Step S150 and Figure 5 Together, they completed the selection of training samples, the construction of auxiliary contexts, and the formation of enhanced training samples 530. Step S160 and Figure 8 Together, they complete the training feedback construction (805) and parameter update (806). The resulting overall chain is not a simple superposition of several independent technical modules, but rather establishes a continuous data flow closed loop between the database execution layer, the sample processing layer, and the model optimization layer.

[0103] Figure 1 If step S110 is missing Figure 2The multi-dialect database execution environment construction shown lacks a constrained basis for subsequent judgments regarding whether candidate SQL sample 304 meets dialect requirements, whether it relies solely on a single database compatibility path, and whether it can be stably executed across database environments. For example, relying solely on a single database execution environment to generate and validate candidate SQL samples can eliminate some obviously grammatically incorrect samples, but it is difficult to identify whether a certain expression is only available in the current database environment. After the model is trained on such samples, once it is migrated to another database environment, even if the natural language problem and database schema are similar, it may output unstable results due to differences in function call methods, null value handling rules, or type comparison rules. By converting database instance 201 into table creation statements and data writing statements 203 through structure normalization and dialect mapping 202, and then establishing the first SQL dialect execution environment 211 and the second SQL dialect execution environment 212 respectively, the same query task 301 can be validated in parallel in multiple SQL dialect environments, thus giving the training samples a natural dialect adaptation constraint.

[0104] Figure 3 The baseline SQL sample 302 plays a crucial role in this training chain, connecting query semantics with dialect implementation. On one hand, the baseline SQL sample 302 corresponds to the core logic of query task 301; on the other hand, it forms the basis for generating candidate SQL samples 304. Without this intermediate layer, the training process might degenerate into directly generating completely independent SQL samples for different database environments. While this would still yield multi-dialect samples, it would be difficult to guarantee sufficient semantic consistency among these samples. For example, in the query task 301 of "counting the number of users placing orders each month," if candidate SQL samples 304 generated in the first SQL dialect execution environment 211 are grouped and counted after deduplication by user, while candidate SQL samples 304 generated in the second SQL dialect execution environment 212 mistakenly use grouping and counting by order count, then while the two are textually valid, they have actually deviated from the same query objective. With the introduction of the baseline SQL sample 302, candidate SQL samples 304 in different dialect environments are all generated around the same semantic skeleton, subsequently... Figure 4 Only the consistency information 406 has a clear reference.

[0105] Figure 4In this embodiment, the execution feedback information not only serves as a verification result but also constitutes important evidence for training sample quality control and parameter updates. Execution status information 403 reflects the basic executability of candidate SQL sample 401 in the current database execution environment 402; result set information 404 reflects the output content of candidate SQL sample 401; dialect constraint verification information 405 reflects whether candidate SQL sample 401 meets the expression requirements corresponding to the current SQL dialect environment; and consistency information 406 reflects its degree of conformity with the baseline execution result. Combining these information provides a more complete training judgment basis than single text alignment. For example, if a candidate SQL sample 401 executes successfully in the current environment but its dialect constraint verification information 405 is unsatisfactory, it may rely on a compatibility path; if another candidate SQL sample 401 fully satisfies the dialect constraints but its consistency information 406 is low, it indicates that although its syntax is correct, it does not accurately express the target semantics of query task 301. After writing this execution feedback information back to the training samples, the model receives not just simple right / wrong signals during training but also difference information containing multi-dimensional constraints.

[0106] Figure 5 The training sample construction and enhancement process in this training chain plays a supplementary role in input robustness. Database schema summary information 511, field value information 512, example information 513, and experience hints 514 can all serve as important reference sources when the natural language to SQL model 802 generates SQL candidates 803. If such auxiliary contextual information is never introduced during training, the model may struggle to fully utilize schema summaries, field value hints, or example recall information in real-world systems during deployment. Conversely, if the training phase consistently assumes that this auxiliary contextual information is always accurate and interference-free, the model may develop an over-reliance on a single hint. Once noisy, redundant, or conflicting hints appear in the context construction in the deployment environment, the model is prone to attention shifts. Figure 5 After the interference information injection module 520 generates enhanced training samples 530, the auxiliary context information 501 in the model input is no longer always the ideal input, but is closer to the input state in the real environment. Then, it is combined with... Figure 8 The execution feedback 804 and training feedback construction 805 in the middle can suppress those erroneous output paths induced by noisy context.

[0107] Figure 8The training feedback construction 805 and parameter update 806 further extend the execution feedback information from the sample processing stage to the model optimization stage. If the training process only compares the lexical differences between the model's output SQL candidate 803 and a certain reference SQL text, the model is easily constrained to a certain reference writing style and it is difficult to fully learn equivalent expressions in different database environments. After introducing execution feedback 804 into the training feedback construction 805, even if the model's output SQL candidate 803 is different from the benchmark SQL sample 302 text, as long as it executes successfully in the target database execution environment 402, the result is consistent, and the dialect constraint is satisfied, it can still obtain a high training feedback value. In this way, the goal of parameter update 806 shifts from "writing like the reference answer" to "executable in the target environment and with correct results". As a result, the model's adaptability to equivalent SQL expressions, dialect differences, and complex query logic is usually more stable.

[0108] This can be combined with a complete scenario description. Figures 1 to 8The collaborative relationship is defined. Database instance 201 may include an order table, a user table, and a region table. Query task 301 is to count the number of users placing orders from a specified region each month in 2024. Step S110 first establishes a first SQL dialect execution environment 211 and a second SQL dialect execution environment 212 based on database instance 201. Step S120 forms a baseline SQL sample 302 corresponding to the query task 301 and generates several natural language samples 303 with different styles. Step S130 generates candidate SQL samples 304 around the first SQL dialect execution environment 211 and the second SQL dialect execution environment 212. Step S140 sends these candidate SQL samples 401 to the corresponding database execution environment 402 for execution. If candidate SQL sample 401 in the first environment can correctly extract dates by month and count the number of unique users, its consistency information 406 is high. If candidate SQL sample 401 in the second environment executes successfully, but the monthly merging result is biased due to the date truncation expression not matching the current dialect environment, its consistency information 406 is low, and the dialect constraint verification information 405 may also indicate that its expression does not conform to the recommended writing style of the current environment. Step S150 can mark the second environment sample as a correctable sample, and call the mapping rule in step S130 to replace the date processing expression and then verify it again. After the corrected sample executes successfully and is consistent with the benchmark execution result, it can be included in the training set along with the first environment sample. If the training sample also includes field value information 512 and example information 513, the interference information injection module 520 can further add similar examples of irrelevant regional values ​​and the number of orders. In step S160, if model 802 is biased by this noise during training, the execution feedback 804 will be reflected in the parameter update 806 through the training feedback construction 805, thereby suppressing the erroneous generation path. As such samples accumulate, the model will form a more stable mapping for query logic under different database environments and complex input conditions.

[0109] From the perspective of the functional subjects involved in the processing Figure 6The training device in the document can implement the aforementioned method steps as a set of collaborative processing modules. The environment construction module 601 receives the database instance 201 and outputs database execution environments corresponding to different SQL dialect environments. The sample generation module 602 receives the database instance 201 and the query task 301, and outputs a baseline SQL sample 302, a natural language sample 303, and candidate SQL samples 304. The execution verification module 603 receives the candidate SQL samples 304 and calls the corresponding database execution environment 402 to complete the verification, outputting execution feedback information. The sample processing module 604 forms training samples and enhanced training samples 530 based on the execution feedback information and auxiliary context information 501. The model optimization module 605 receives the training samples, execution feedback 804, and model output SQL candidates 803, constructs training feedback 805, and updates the model parameters 806. Figure 6 These modules can be deployed in the same server cluster or distributed across different nodes, exchanging data through message queues, remote calls, or shared storage.

[0110] In one embodiment, the environment building module 601 is more suitable for deployment on processing nodes with similar database management capabilities. Its function is not simply to copy table structures, but to extract a unified semantic structure from the database instance 201 and then implement it in different database execution environments. If multiple training tasks run concurrently in the deployment system, the environment building module 601 can maintain independent environment instance pools for different tasks. One consideration for this is that the database instances corresponding to different training tasks may have different sizes and structural styles, and the use of environment resources should not interfere with each other; another consideration is that the execution verification phase may require repeated verification of the same candidate SQL sample 304, and independent environment instance pools help shorten environment reconstruction time. For smaller database instances 201, a lightweight environment reuse approach can also be adopted, that is, retaining table creation and data writing results, and only resetting the session state when switching tasks.

[0111] Sample generation module 602 in Figure 6The sample generation module 602 undertakes two levels of tasks. The first level involves generating a baseline SQL sample 302 and a natural language sample 303 around query task 301. The second level involves generating candidate SQL samples 304 based on different SQL dialect environments. When generating the baseline SQL sample 302, the focus is on the accuracy of the query logic, its coverage of different complexities, and its consistency with the structure in database instance 201. When generating candidate SQL samples 304, the focus is on whether the differences in expression of the same logic in different dialect environments are correctly converted. To this end, the sample generation module 602 can further include a structure parsing submodule, a semantic mapping submodule, and a dialect rewriting submodule. The structure parsing submodule is used to extract tables, fields, joins, filters, and aggregation relationships; the semantic mapping submodule is used to align query task 301 with the baseline SQL sample 302 and the natural language sample 303; and the dialect rewriting submodule is used to convert the baseline SQL sample 302 into candidate SQL samples 304 for different environments.

[0112] Execution verification module 603 and Figure 4 The execution verification process is shown below. This module is not required to process only a single candidate SQL sample 304 at a time; it can also process multiple samples in batches. During batch processing, samples can be grouped according to the target SQL dialect environment and then submitted to different database execution environments 402. This reduces the overhead of environment switching and connection establishment. One problem with batch processing is that the execution time of different samples may vary significantly. To avoid waiting for the longest sample, the execution verification module 603 can adopt an asynchronous recycling mechanism. Once a candidate SQL sample 304 obtains the execution status information 403, result set information 404, and dialect constraint verification information 405, it can be written to the execution feedback record. If consistency information 406 needs to be formed, it can be written later when the baseline execution result is available. Through this asynchronous recycling method, the sample processing module 604 can receive execution results in batches without waiting for the entire batch to complete.

[0113] The sample processing module 604 is responsible for converting execution results into trainable data. If this module only performs simple filtering, the advantage of the entire training chain will be weakened. Therefore, in one embodiment, the sample processing module 604 may include a filtering submodule, a labeling submodule, an adjustment submodule, and an enhancement submodule. The filtering submodule is responsible for removing candidate SQL samples that are obviously erroneous and cannot be repaired. The labeling submodule is responsible for converting execution status, result consistency, and dialect adaptation into labels. The adjustment submodule is responsible for making partial modifications to some repairable samples and sending them back to the execution verification module 603. The enhancement submodule, along with... Figure 5The interference information injection module 520 works in conjunction with the auxiliary context information 501 to organize it into enhanced training samples 530 that can be used for training. Through this organization, the sample processing module 604 preserves both the constraints brought about by the execution feedback and the input perturbations related to robust training.

[0114] Model optimization module 605 and Figure 8 The training feedback construction 805 and parameter update 806 correspond to each other. In one embodiment, the model optimization module 605 can receive three types of inputs. The first type is the training samples themselves, including natural language samples 303, candidate SQL samples 304 or their label representations, and auxiliary context information 501. The second type is execution feedback 804, which can come from offline constructed sample labels or from feedback obtained from online execution in the current training round. The third type is the current model output SQL candidate 803. When processing these three types of inputs, the model optimization module 605 does not simply select one of them as the sole basis, but organizes them into training feedback 805 that can drive parameter update 806. If the execution feedback 804 of a certain sample is stable enough, the training feedback 805 can rely more on the execution result; if the output path of a certain sample changes significantly in the current training round, the training feedback 805 can also refer to text-level structural errors to make the parameter update process smoother.

[0115] Figure 7 The illustrated electronic device can be used to implement the foregoing method embodiments and apparatus embodiments. The electronic device includes a processor 701, a memory 702, a communication interface 703, and a bus 704. The processor 701 can be a general-purpose central processing unit or a dedicated computing processor suitable for model training tasks. The memory 702 can store data for implementing... Figures 1 to 8 The illustrated process includes a computer program, sample cache, execution feedback records, and model parameters. Communication interface 703 is used to exchange data with the database execution environment, external storage system, or other training nodes. Bus 704 connects processor 701, memory 702, and communication interface 703. When processor 701 executes the computer program in memory 702, it enables the electronic device to complete... Figure 1 The steps S110 to S160 correspond to the following processing steps: database instance acquisition, database execution environment construction, sample generation, execution verification, sample processing, and model parameter updating.

[0116] In one embodiment, the electronic device can be a training server or a computing node that simultaneously possesses database processing and model training capabilities. If the training pipeline adopts a distributed deployment, then Figure 7 Electronic devices in a system can perform only a portion of the processing. For example, one type of electronic device can primarily handle... Figure 6The functions corresponding to the environment construction module 601 and the execution verification module 603 in the middle; another type of electronic device can mainly undertake Figure 6 The model optimization module 605 corresponds to this function. The two types of devices can transmit execution feedback information and training samples through the communication interface 703. In resource-constrained scenarios, the execution verification environment can also be deployed in a container, with a single physical server hosting multiple logical database execution environments. In this case, the processor 701 is responsible for container management, SQL execution scheduling, and feedback collection, while the memory 702 is responsible for caching database instance snapshots and training batch data. For this solution, the key is not the number of physical devices, but rather the execution verification capability under different SQL dialect environments and the ability to reuse execution feedback.

[0117] In one embodiment, Figure 7 The corresponding computer program can be stored in a computer-readable storage medium. This storage medium can be a disk, solid-state storage, flash memory, read-only memory, or other non-transitory storage medium that can be read by a processor. When the computer program is loaded and executed, the electronic device can perform the aforementioned training method. Specifically, the computer program can include an environment building instruction set, a sample generation instruction set, an execution verification instruction set, a sample processing instruction set, and a model optimization instruction set. The environment building instruction set is used to generate table creation statements and data writing statements 203 suitable for different SQL dialect environments based on the database instance 201; the sample generation instruction set is used to form baseline SQL samples 302, natural language samples 303, and candidate SQL samples 304; the execution verification instruction set is used to call the database execution environment 402 and collect execution feedback information; the sample processing instruction set is used to construct training samples and enhance training samples 530; and the model optimization instruction set is used to construct training feedback 805 and update model parameters 806.

[0118] In a specific deployment scenario, if the training tasks originate from multiple business domains within an enterprise, the structural style of database instance 201 may vary significantly. In some business domains, field names are closely related to business semantics, making it relatively easy to form natural language samples 303 around them; however, other business domains may have numerous abbreviated fields, historically compatible fields, or redundant fields. In such cases, relying solely on field names can easily lead to unstable semantic correspondence between the baseline SQL sample 302 and the natural language sample 303. Faced with this situation, Figure 6 The sample processing module 604 and model optimization module 605 can rely more heavily on field value information 512 and experience hint information 514 to enhance the auxiliary context. If the data distribution in certain business domains changes over a long period, such as the order status enumeration continuously expanding, then... Figure 6The environment building module 601 can also attach a version identifier to the database instance 201 when building the database execution environment. In this way, the training samples can record the source environment version, and the model optimization module 605 can distinguish the constraint differences brought by different database versions during training, thereby avoiding the misgeneralization of old version field values ​​or old version dialect behaviors to all training scenarios.

[0119] By adopting the technical solutions in the aforementioned embodiments, at least two database execution environments corresponding to SQL dialect environments are established around the same database instance 201, and the candidate SQL samples 304 are executed and verified in different SQL dialect environments. This allows the training samples to include database environment constraints and execution result constraints before entering model training, thereby reducing the situation where the natural language to SQL model 802 relies solely on a single dialect expression for learning. By introducing execution status information 403, execution result information 404, dialect constraint verification information 405, and consistency information 406 into step S150, and further constructing training feedback 805 in step S160 to participate in model parameter updates, the model's learning objective can be made closer to the executability and correctness of results in the real database, rather than just approaching the reference SQL text. By introducing auxiliary context information 501, consisting of database schema summary information 511, field value information 512, example information 513, and experience hint information 514, into the training stage, and forming enhanced training samples 530 through the interference information injection module 520, the training process can also cover input forms closer to real deployment conditions, thereby improving the stability of the model under complex input conditions.

[0120] From an overall mechanism perspective, database instance 201 provides a unified semantic source. Figure 2 The structure normalization and dialect mapping in section 202 expands this semantic source to different SQL dialect execution environments. Figure 3 The baseline SQL sample 302 and natural language sample 303 transform query task 301 into standardized semantics and diverse expressions. Figure 4 The execution verification process transforms the behavior of candidate SQL sample 401 in the real database execution environment 402 into execution feedback information. Figure 5 The auxiliary context information 501 and the enhanced training samples 530 in the training process move common prompts and noise conditions encountered in real deployments to the training phase. Figure 8The training feedback construction (805) and parameter update (806) further transform the execution feedback into a basis for model optimization. The resulting training chain does not treat database execution merely as an additional validation step after training, but rather embeds database execution feedback into both training sample formation and model parameter update. Thus, the natural language to SQL model (802) learns not only static SQL text, but also query generation capabilities with database environment constraints, execution result constraints, and contextual noise constraints.

[0121] In one different embodiment, Figure 2 The SQL dialect environments are not limited to two; they can be extended to three or more. During extension, database instance 201 still serves as a unified semantic source, with each dialect environment corresponding to a separate database execution environment. If a dialect environment has unique functional differences only on a small number of samples, these differences can be extracted into a specialized set of mapping rules and applied as needed in the generation process of candidate SQL samples 304 in step S130. If multiple database systems in the deployment scenario are similar in most basic syntaxes, with only local differences in date, string, or null value handling, step S130 can only replace these local differences without completely rewriting the query structure. This approach reduces the engineering overhead of dialect extension while maintaining the semantic uniformity of the training data.

[0122] In one different embodiment, Figure 5 The auxiliary context information 501 is not always required to include the four items: database schema summary information 511, field value information 512, example information 513, and experience hints 514. In deployment scenarios sensitive to input length, the auxiliary context information 501 can include only the database schema summary information 511 and field value information 512, without providing example information 513 or experience hints 514. Conversely, in scenarios with complex database schemas and less intuitive field naming, the proportion of example information 513 and experience hints 514 can be appropriately increased to help the model establish the correspondence between fields and business semantics. Regardless of the organization method used, Figure 5 The interference information injection module 520 can all work, but the injection object will be adjusted accordingly based on the currently retained auxiliary context item.

[0123] In one different embodiment, Figure 8The training feedback construct 805 can also set different sensitivities for different types of execution feedback. Syntax execution errors typically indicate incompatibility between the candidate SQL sample 304 and the target database execution environment at the expression level, thus making them more suitable as strong negative signals; inconsistent results reflect semantic bias more, and their severity can be determined based on the consistency score; unmet dialect constraints sometimes do not lead to immediate errors, but reflect instability in the expression, making them more suitable as moderate-strength constraint signals. Through this differentiated design, parameter updates 806 can more quickly distinguish between syntax adaptation problems, semantic bias problems, and compatibility boundary problems, helping to shorten the time it takes for the model to learn stable expressions.

[0124] In one different embodiment, the candidate SQL samples 304 generated in step S130 do not necessarily have to be entirely generated by rule mapping; they can also be partially provided by an automatically generated model and then processed... Figure 4 The execution verification process filters and corrects errors. In this implementation, rule mapping primarily provides basic constraints, while automatically generated models cover more complex variations in expression. Because... Figure 4 and Figure 5 The execution feedback and context enhancement chains still exist. Errors introduced during automatic generation will not directly enter the training set, but must first undergo execution verification and sample processing. This approach is more suitable for scenarios with large sample sizes and the need to expand complex query expressions. It also helps reduce the cost of relying entirely on manual rule maintenance when database schemas change frequently in the business domain.

[0125] In one different embodiment, the database execution environment 402 can be deployed either on a remote database cluster or in a local containerized environment. Remote deployment is suitable for scenarios with relatively complete existing database infrastructure, while local containerized deployment is suitable for scenarios requiring rapid replication of multi-dialect environments and large-scale parallel verification. Different deployment methods do not substantially affect steps S110 to S160 themselves; the main differences lie in the environment build time, execution latency, and resource scheduling methods. If there is network jitter in the remote environment, the execution verification module 603 can add result retry or delay recording to avoid misjudging network fluctuations as SQL execution failure. If the local containerized environment has limited resources, it can be addressed through… Figure 6 The asynchronous queue between modules controls the concurrency, avoiding excessive resource contention between execution environments that could lead to an increase in timeout samples.

[0126] In one different embodiment, query task 301 may be for a single round of input or may include prior context. In the case of prior context, natural language sample 303 may consist of the current round question and historical questions, while auxiliary context information 501 may add historical query summaries. In this case, baseline SQL sample 302 reflects not only the current question but also the limitations imposed on the current question by the historical context. Candidate SQL sample 304 can still be generated according to step S130 and validated according to step S140 in different database execution environments 402. For this type of scenario, the value of execution feedback information is particularly evident because historical context often introduces ellipsis and pronouns, making it more difficult to determine whether candidate SQL sample 304 truly conforms to the target semantics simply by relying on text alignment.

[0127] The aforementioned implementation methods can be combined or selected according to the scenario. For scenarios with fewer types of database systems but significant variations in business expressions, greater emphasis can be placed on the construction of natural language samples 303 and augmented training samples 530. For scenarios with significant differences in database systems and frequent cross-environment deployments, greater emphasis can be placed on... Figure 2 and Figure 4 The corresponding multi-dialect execution verification process. For scenarios with low input noise but strict requirements for execution correctness, the proportion of interference information injection can be appropriately reduced, while the training focus is placed on utilizing consistency information 406 and dialect constraint verification information 405. Although the parameter range, deployment location, and sample organization strategy may differ in different implementation methods, the main chain of building a multi-dialect database execution environment around the database instance, generating baseline SQL samples and candidate SQL samples, performing verification, sample processing, and updating model parameters based on execution feedback remains unchanged.

[0128] It should be understood that the method steps in the foregoing embodiments can be implemented by program instructions controlling related hardware, or by dedicated circuits, programmable logic devices, or a combination thereof. Correspondingly, the systems, devices, modules, units, or components in the foregoing embodiments can be implemented in software, hardware, or a combination of both. The division of modules, units, or components is merely a logical division for the purpose of illustrating the technical solution; in actual implementation, they can be combined, split, or integrated as needed.

[0129] In one embodiment, the electronic device may include a processor, a memory, and a communication interface, wherein the memory is used to store program instructions, and the processor is used to call and execute the program instructions to implement all or part of the steps in the foregoing method embodiments. The electronic device may be a server, a terminal device, an edge computing node, a cloud computing device, or other device with data processing capabilities.

[0130] In one embodiment, this application may also be implemented in the form of a computer-readable storage medium. The computer-readable storage medium stores a computer program, which, when executed by a processor, causes the processor to implement all or part of the steps in the foregoing method embodiments. The computer-readable storage medium may be a read-only memory, random access memory, flash memory, hard disk, solid-state drive, optical disk, or other non-transitory storage medium.

[0131] The various embodiments in this specification are described in a progressive manner. Similar or identical parts between embodiments can be referred to mutually. Each embodiment focuses on describing the differences from other embodiments. In particular, system embodiments are basically similar to method embodiments, so the description is relatively simple; relevant parts can be referred to the descriptions in the method embodiments. In the description of this specification, the terms "one embodiment," "some embodiments," "example," "specific example," or "some examples," etc., refer to specific features, structures, materials, or characteristics described in connection with that embodiment or example, which are included in at least one embodiment or example of this specification. In this specification, the illustrative expressions of the above terms do not necessarily refer to the same embodiment or example. Furthermore, the specific features, structures, materials, or characteristics described can be combined in any suitable manner in one or more embodiments or examples. Moreover, without contradiction, those skilled in the art can combine and integrate the different embodiments or examples described in this specification and the features of different embodiments or examples.

[0132] Furthermore, the terms "including," "comprising," and "having" used in the specification are all non-exclusive inclusions; the terms "first," "second," etc., are only used to distinguish technical features and do not indicate limitations on order, quantity, or importance. The execution order of each step in the method embodiments is not strictly limited. Without departing from the technical concept of this application, the steps can be adjusted in order, executed in parallel, combined, or split.

Claims

1. A training method for a natural language to SQL model, applied to database execution environments corresponding to at least two SQL dialect environments, the training method comprising: Obtain a database instance, and construct a database execution environment based on the database instance that corresponds to the at least two SQL dialect environments respectively; Based on the database instance, a baseline SQL sample corresponding to the query task is generated, as well as a natural language sample corresponding to the semantics of the baseline SQL sample; Based on the at least two SQL dialect environments, candidate SQL samples in the corresponding SQL dialect environments are generated from the baseline SQL samples. The candidate SQL samples are sent to the corresponding database execution environment for execution verification to obtain execution feedback information, which includes at least one of execution status information and execution result information. Based on the execution feedback information, the natural language samples, the baseline SQL samples, and the candidate SQL samples are filtered, labeled, or adjusted to obtain training samples. The natural language to SQL model is trained using the training samples, and training feedback is constructed based on the execution feedback information during the training process to update the parameters of the natural language to SQL model.

2. The training method as described in claim 1, wherein, Based on the database instance, database execution environments corresponding to the at least two SQL dialect environments are constructed, including: Based on the table structure and data content of the database instance, generate table creation statements and data writing statements suitable for the at least two SQL dialect environments respectively; Based on the table creation statement and the data writing statement, a database execution environment is established in the corresponding database system.

3. The training method as described in claim 1, wherein, Based on the database instance, a baseline SQL sample corresponding to the query task is generated, along with natural language samples corresponding to the semantics of the baseline SQL sample, including: Generate benchmark SQL samples of different difficulty levels according to preset complexity rules; For each of the aforementioned benchmark SQL samples, generate at least two natural language samples with semantically equivalent expression styles to the benchmark SQL samples.

4. The training method as described in claim 1, wherein, The execution feedback information includes at least one of the following: Success or failure information of candidate SQL samples in the corresponding database execution environment; Result set information of candidate SQL samples in the corresponding database execution environment; Verification information on whether candidate SQL samples meet the constraints of the corresponding SQL dialect environment; Consistency information regarding whether the execution results of the candidate SQL sample are consistent with the baseline execution results.

5. The training method as described in claim 1, wherein, Based on the execution feedback information, the natural language samples, the baseline SQL samples, and the candidate SQL samples are subjected to sample filtering, sample annotation, or sample adjustment to obtain training samples, including: Eliminate candidate SQL samples that fail to execute in the corresponding database execution environment; Candidate SQL samples that execute successfully but whose results are inconsistent with the baseline execution results are marked with errors or adjusted. Candidate SQL samples that are successfully executed and whose execution results are consistent with the baseline execution results are retained as part of the training samples.

6. The training method as described in claim 1, wherein, Before obtaining the training samples, the following is also included: Construct auxiliary context information for the natural language sample or the benchmark SQL sample, the auxiliary context information including at least one of the following: Database schema summary information; Field value information related to the query task; Example information related to the query task; Tips and experiences related to the query task; Interference information is added to the auxiliary context information to obtain enhanced training samples in the training samples.

7. The training method as described in claim 6, wherein, Adding interference information to the auxiliary context information to obtain enhanced training samples in the training samples includes: Add irrelevant field values ​​to the field value information related to the query task; Add distracting examples to the example information related to the query task; Add redundant tips that do not correspond to the baseline SQL sample to the experience tips related to the query task.

8. A training device for a natural language to SQL model, comprising: An environment building module is used to obtain a database instance and build a database execution environment based on the database instance, which corresponds to at least two SQL dialect environments respectively; The sample generation module is used to generate a baseline SQL sample corresponding to the query task based on the database instance, and a natural language sample corresponding to the semantics of the baseline SQL sample, and to generate candidate SQL samples in the corresponding SQL dialect environment based on the at least two SQL dialect environments. The execution verification module is used to send the candidate SQL samples to the corresponding database execution environment for execution verification and obtain execution feedback information. The sample processing module is used to perform sample filtering, sample annotation, or sample adjustment on the natural language samples, the benchmark SQL samples, and the candidate SQL samples based on the execution feedback information to obtain training samples; The model optimization module is used to train the natural language to SQL model using the training samples, and to construct training feedback based on the execution feedback information during the training process to update the parameters of the natural language to SQL model.

9. An electronic device comprising a processor and a memory, the memory storing a computer program that, when executed by the processor, causes the electronic device to perform the training method as described in any one of claims 1 to 7.

10. A computer-readable storage medium storing a computer program that, when executed by a processor, causes the processor to perform the training method as described in any one of claims 1 to 7.