我有一個包含許多創建表 ddl 的檔案 master.sql。
主.sql
CREATE TABLE customers (
customer_id numeric(38) GENERATED BY DEFAULT AS IDENTITY,
email_address varchar(255) NOT NULL,
full_name varchar(255) NOT NULL
) ;
CREATE TABLE inventory (
inventory_id numeric(38) GENERATED BY DEFAULT AS IDENTITY,
store_id numeric(38) NOT NULL,
product_id numeric(38) NOT NULL,
product_inventory numeric(38) NOT NULL
) ;
我想將此檔案拆分為單獨的檔案 - 每個檔案一個表。為此,我在這里使用rubin 的解決方案。
這是我使用的 awk 命令。
awk '/CREATE TABLE/{f=0 ;n ; print >(file=n); close(n-1)} f{ print > file}; /CREATE TABLE/{f=1}' master.sql
在執行 awk 命令時,會生成具有表數且沒有任何擴展名的檔案。嘗試使用本文聯系
創建每個 sql 檔案時,我想更改表名的檔案名。
例如。
客戶.sql
庫存.sql
我正在嘗試使用 awk 命令從 master.sql 中獲取表名。迭代master.sql時是否可以獲取表名。
有沒有解決的辦法 ?
uj5u.com熱心網友回復:
嗨,你可以使用類似的東西:
awk 'BEGIN{RS=";"} /CREATE TABLE/{fn = $3 ".sql"; print $0 ";" > fn; close(fn);}' master.sql
該BEGIN塊將使用;字符作為記錄分隔符將輸入拆分為 sql 陳述句(而不是行)。
如果該行與CREATE TABLE基于第三個欄位(表名)的檔案名匹配,則可以列印陳述句內容
注意:如果有任何 sql 注釋包含 ;
編輯關閉檔案(參見@ed-morton 的評論)
uj5u.com熱心網友回復:
你使用的那個 awk 命令對于你正在做的事情來說是非常復雜的。它所需要的只是:
awk '/CREATE TABLE/{close(n); n } {print > n}' file
對于您的新要求,它只是一個調整:
$ awk '/CREATE TABLE/{close(out); out=$3 ".sql"} {print > out}' file
$ head *.sql
==> customers.sql <==
CREATE TABLE customers (
customer_id numeric(38) GENERATED BY DEFAULT AS IDENTITY,
email_address varchar(255) NOT NULL,
full_name varchar(255) NOT NULL
) ;
==> inventory.sql <==
CREATE TABLE inventory (
inventory_id numeric(38) GENERATED BY DEFAULT AS IDENTITY,
store_id numeric(38) NOT NULL,
product_id numeric(38) NOT NULL,
product_inventory numeric(38) NOT NULL
) ;
uj5u.com熱心網友回復:
這是一個簡單的兩步程序:
# Split the files when the string CREATE TABLE is found
csplit master.sql '/CREATE TABLE/'
# Read the first line, extract table name and rename the file
for f in $(ls xx*);
do
table_name=`head -1 $f | awk '{ sub(/.*CREATE TABLE /, ""); sub(/ .*/, ""); print }'`
mv $f "$table_name.sql"
echo "Renaming $f to $table_name.sql";
done;
->
Renaming xx00 to customers.sql
Renaming xx01 to inventory.sql
->
$ ls
customers.sql inventory.sql master.sql
$ cat customers.sql
CREATE TABLE customers (
customer_id numeric(38) GENERATED BY DEFAULT AS IDENTITY,
email_address varchar(255) NOT NULL,
full_name varchar(255) NOT NULL
) ;
$ cat inventory.sql
CREATE TABLE inventory (
inventory_id numeric(38) GENERATED BY DEFAULT AS IDENTITY,
store_id numeric(38) NOT NULL,
product_id numeric(38) NOT NULL,
product_inventory numeric(38) NOT NULL
) ;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408171.html
標籤:
