2013-12-17 20 views
0

我已經在青梅創建的表,下面是腳本青梅(Postgres的SQL)

- 表:staging.file_data

- DROP TABLE staging.file_data;

CREATE TABLE staging.file_data 
(
    file_name character varying(28), 
    line_number integer, 
    date_line text 
) 
WITH (
    OIDS=FALSE 
) 
DISTRIBUTED BY (file_name); 
ALTER TABLE staging.file_data 
    OWNER TO dev_staging_develop; 

現在我需要加載該表與一些平面文件.... 平面文件有更多的列,但有人問我與平面文件加載該表作爲 1.第一列具有文件名稱 2.第二列是序號(行號) 3第三列將有一串數據(它不過是平面文件第一行中的所有數據)並且每個數據都是相同的排。

所以如果平面文件有100條記錄,我們將在表中有100行。

但我不知道如何將此平面文件導入到此表中,任何人都可以幫助 注意:平面文件是一個文本文件。並位於我的本地機器上。

感謝您的時間和事先幫助。

傑森

+0

大家好,我已經在這裏創造了表腳本 – jason

+0

我認爲'date_line'是爲'名不副實data_line' –

+0

你看:http://www.postgresql.org /docs/8.4/interactive/sql-copy.html和http://stackoverflow.com/questions/2987433/how-to-import-csv-file-data-into-a-postgres-table –

回答

0

好讀,你需要將其加載到一個表的文件,但是如果您想要額外的域不屬於平面文件的一部分,您需要在那裏建立一箇中間步驟。事情是這樣的:

--Create a temporary table to hold the contents of the file 
create temp table temp_file (
each_line text 
); 

copy temp_file from '<path_to_file>/filename' text HEADER; 
--if the file has a header! See also delimiter if needed and choose a char that does not exist in the file 

--Now add the line numbers, and the filename 
alter table temp_file add column line_no smallint; 
alter table temp_file add column filename text; 
create sequence temp_file_seq increment by 1 start with 1; --not sure start with 1 or 0, try 

update temp_file 
set line_no = nextval('temp_file_seq') 
    ,filename = 'filename'; 

--Now populate your table 
insert into staging.file_data 
select * from temp_file; 

--Cleanup 
drop table temp_file;