SQL/Regex Challenge/Puzzle:如何从 SQL 代码中删除注释(通过使用 SQL 查询)?

SQL/Regex Challenge/Puzzle: How to remove comments from SQL code (by using SQL query)?

要求

文字和标识符

文字和标识符可以跨越多行

单行注释

单行注释可能是代码的最后一个元素,可能不会以换行符结尾。

嵌套多行注释

在SQLServer和PostgreSQL等数据库中,可以嵌套多行注释,如-

/* outer comment /* inner comment */ */

以下代码无效,因为只关闭了内部评论:

/* opened outer comment /* closed inner comment */

在 Teradata、Oracle、MySql 和 SQLite 等数据库中,没有嵌套注释的概念。 以下代码无效,因为注释已经用最左边的 */.

关闭
/* comment /* is closed */ ERROR */

然而,这是一个有效的代码:

/* comment /* still the same comment */

解决方案

Teradata

with t (txt) as 
(
select     '
            select    /* comment /* yada yada yada /* / // bla bla bla  
                        1
                                    */ t1.i
                   ,''"SRC''''"''    as "This''is''the
                                ''source"

            from      t1 /* "Comment 2" - '' */ cross join t2 -- /* comment 3 */

            where     t2.v = ''/*DST"*
                                /'' -- comment 4'
)

select    regexp_replace (txt,'(''.*?''|".*?")|/\*.*?\*/|--.*?(?=[\r\n]|$)','',1,0,'n')     as clean_txt

from      t
;

甲骨文

with t (txt) as 
(
select     '
            select    /* comment /* yada yada yada /* / // bla bla bla  
                        1
                                    */ t1.i
                   ,''"SRC''''"''    as "This''is''the
                                ''source"

            from      t1 /* "Comment 2" - '' */ cross join t2 -- /* comment 3 */

            where     t2.v = ''/*DST"*
                                /'' -- comment 4'

from        dual
)

select    regexp_replace (txt,'(''.*?''|".*?")|/\*.*?\*/|--.*?(?=$|\Z)','',1,0,'nm')

from      t
;

结果

            select     t1.i
                   ,'"SRC''"'    as "This'is'the
                                'source"

            from      t1  cross join t2 

            where     t2.v = '/*DST"*
                                /'