2010-08-16 100 views
0

我有一系列的像這樣的SQL腳本:清理CREATE TABLE列布局

CREATE TABLE table_one 
(
    column_one   int not null, 
    column_two varchar(100)    not null, 
    column_three_four_five int, 
    column_six decimal(16,4) null, 
    PRIMARY KEY (column_one, column_three_four_five) 
); 

我想清理佈局更容易掃描,這樣的事情:

CREATE TABLE table_one 
(
    column_one    int   not null, 
    column_two    varchar(100) not null, 
    column_three_four_five int, 
    column_six    decimal(16,4)  null, 
    PRIMARY KEY 
    (
     column_one, 
     column_three_four_five 
    ) 
); 

確切的佈局並不比創建乾淨的外觀以提高可讀性要重要。 (閱讀:請不要火焰格式本身)-grin-

什麼是一個好方法腳本(我看着你,Perl的神......)?

+1

你知道,諸如「Perl gods」(小* g *不少於),「大師」,「黑客」等短語在一段時間後開始失去原創性(!)。 – 2010-08-16 03:49:09

+0

只有一個問題是那些表格和空間還是隻有一個? – Prix 2010-08-16 03:49:34

+0

@Prix:空格,保持簡單。我不尋找花哨,只是乾淨:) – 2010-08-16 03:52:16

回答

2

Hmmmmm也不能說這會爲您的所有文件工作,但像這樣的做的工作......

#!/usr/bin/perl 
use strict; 
use warnings; 

my $default_padding = 30; 
my $my_file = 'data.sql'; 
my $my_new_file = 'data_new.sql'; 

open (my $fh, '<', $my_file) or die $!; 
my @sql = <$fh>; 
close($fh); 

open (my $fhsave, '>>', $my_new_file) or die $!; 
foreach my $line (@sql) { 
    print $fhsave "$line" if ($line !~ /^\s+/); 
    $line =~ s/\s+/ /ig; 
    print $fhsave sprintf(" %-*s %s\n", $default_padding, $1, $2) if ($line =~ /^\s+(.+?)\s+(.+)/); 
} 
close ($fhsave); 

樣本文件data.sql

CREATE TABLE table_one 
(
    column_one   int not null, 
    column_two varchar(100)    not null, 
    column_three_four_five int, 
    column_six decimal(16,4) null 
); 

輸出:

CREATE TABLE table_one 
(
    column_one      int not null, 
    column_two      varchar(100) not null, 
    column_three_four_five   int, 
    column_six      decimal(16,4) null 
); 
+0

謝謝,Prix!而已。簡單,乾淨,正是我所需要的。 – 2010-08-16 17:24:51

0

http://www.dpriver.com/pp/sqlformat.htm

不是腳本。但我現在不想編碼任何東西。

對於像這樣的東西在任何語言尋找格式化程序或單詞'漂亮'預構建垃圾。

+0

偉大的網站。會很常規,但我在各種討厭的狀態中繼承了大約300個這樣的腳本。儘管如此,感謝您的鏈接。 – 2010-08-16 03:57:58

1

我還沒有嘗試過任一種,但CPAN有SQL::BeautifySQL::QueryBuilder::Pretty

+0

這些都很好,但第二個不知道CREATE TABLE是什麼,並且會搞砸,第一個格式非常好,但在新行和括號中存在一些問題。它們似乎更適合於選擇,刪除,更新查詢。 – Prix 2010-08-16 04:59:50