Postgresql: inserting value of a column from a file

后端 未结 2 1132
不知归路
不知归路 2020-12-28 08:19

For example, there is a table named \'testtable\' that has following columns: testint (integer) and testtext (varchar(30)).

What i want to do is pretty much somethin

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-28 09:06

    If I understand your question correctly, you could read the single string(s) into a temp table and use that for insert:

    DROP SCHEMA str CASCADE;
    CREATE SCHEMA str;
    
    SET search_path='str';
    
    CREATE TABLE strings
        ( string_id INTEGER PRIMARY KEY
        , the_string varchar
        );
    CREATE TEMP TABLE string_only
        ( the_string varchar
        );
    
    COPY string_only(the_string)
    FROM '/tmp/string'
        ;   
    
    INSERT INTO strings(string_id,the_string)
    SELECT 5, t.the_string
    FROM string_only t
        ;   
    
    SELECT * FROM strings;
    

    Result:

    NOTICE:  drop cascades to table str.strings
    DROP SCHEMA
    CREATE SCHEMA
    SET
    NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "strings_pkey" for table "strings"
    CREATE TABLE
    CREATE TABLE
    COPY 1
    INSERT 0 1
     string_id |     the_string      
    -----------+---------------------
             5 | this is the content
    (1 row)
    

    Please note that the file is "seen" by the server as the server sees the filesystem. The "current directory" from that point of view is probably $PG_DATA, but you should assume nothing, and specify the complete pathname, which should be reacheable and readable by the server. That is why I used '/tmp', which is unsafe (but an excellent rendez-vous point ;-)

提交回复
热议问题