【问题标题】:How/where to format INSERT statement by aligning columns with values如何/在何处通过将列与值对齐来格式化 INSERT 语句
【发布时间】:2022-11-29 14:19:41
【问题描述】:

我想知道如何格式化 INSERT 语句:

INSERT tablename ([column1], [column2], [column3], [column4], [column5]) VALUES (2,1,11,NULL,4), (2,1,11,NULL,4), (2,1,11,NULL,4);

至:

INSERT tablename ([column1], [column2], [column3], [column4], [column5]) 
          VALUES (        2,         1,        11,      NULL,         4),
                 (        2,         1,        11,      NULL,         4),
                 (        2,         1,        11,      NULL,         4);

你知道一些文本格式化程序吗?

我找到了几个选项,但没有一个是那样做的。

【问题讨论】:

    标签: sql insert format


    【解决方案1】:

    我没有找到现成的解决方案,所以我用 PHP 来解决。

    让我知道任何问题,

    享受!

    #!/usr/bin/env php
    <?php
    echo preg_replace_callback("/(INSERT)s+(.+)s+((.+))s+(VALUES)s+((.+));*/", function($matches) {
        $columns = explode(",", $matches[3]);
        $values  = explode(",", $matches[5]);
    
        //length of INSERT + tablename
        $length = strlen("$matches[1] $matches[2]");
        //fills VALUES with leading spaces
        $values_with_spaces = str_pad($matches[4], $length, " ", STR_PAD_LEFT);
    
        $newColumns = $newValues = [];
        foreach($columns as $key => $column) {
            $value = !isset($values[$key]) ? 'NULL' : $values[$key];
    
            //takes the longest length between the column and the value
            $column_length = max(strlen($column), strlen($value));
    
            $newColumns[$key] = str_pad($column, $column_length, " ", STR_PAD_LEFT);
            $newValues[$key]  = str_pad($value, $column_length, " ", STR_PAD_LEFT);
        }
    
        return "$matches[1] $matches[2] (".join(",",$newColumns).")
    $values_with_spaces (".join(",",$newValues).");
    ";
    }, file_get_contents("php://stdin"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-26
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      • 2012-11-24
      相关资源
      最近更新 更多