Postgresql: inserting value of a column from a file

后端 未结 2 1114
不知归路
不知归路 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 08:56

    If this SQL code is executed dynamically from your programming language, use the means of that language to read the file, and execute a plain INSERT statement.

    However, if this SQL code is meant to be executed via the psql command line tool, you can use the following construct:

    \set content `cat file`
    INSERT INTO testtable VALUES(15, :'content');
    

    Note that this syntax is specific to psql and makes use of the cat shell command.

    It is explained in detail in the PostgreSQL manual:

    • psql / SQL Interpolation
    • psql / Meta-Commands
    0 讨论(0)
  • 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 ;-)

    0 讨论(0)
提交回复
热议问题