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

前端 未结 1 1121
挽巷
挽巷 2021-01-24 16:27

Requirements

  • Single-lines comments (e.g. -- my comment) should be removed.
  • Multi-line comments (e.g. /* my comment */) should be removed.
  • The co
相关标签:
1条回答
  • 2021-01-24 16:40

    Solutions

    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',1,0,'n')     as clean_txt
    
    from      t
    ;
    

    Oracle

    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',1,0,'nm')
    
    from      t
    ;
    

    Result

                select     t1.i
                       ,'"SRC''"'    as "This'is'the
                                    'source"
    
                from      t1  cross join t2 
    
                where     t2.v = '/*DST"*
                                    /'
    
    0 讨论(0)
提交回复
热议问题