【问题标题】:How do I add timestamp (using GETDATE()) to my insert statement?如何将时间戳(使用 GETDATE())添加到我的插入语句中?
【发布时间】:2023-01-13 15:52:38
【问题描述】:

我想弄清楚如何将时间戳添加到我的数据库表中。 df2 不包含任何时间列,因此我试图在 values_ 或执行 sql 时创建值。我想使用 GETDATE() 红移函数

  values_ = ', '.join([f"('{str(i.columnA)}','{str(i.columnB)}','{str(i.columnC)}','{str(i.columnD)}', 'GETDATE()')" for i in df2.itertuples()])
        
        sqlexecute(f'''insert into table.table2 (columnA, columnB, columnC, columnD, time_) 
                values
        ({values_})
        ;
        ''')

这是我遇到的几个错误之一,具体取决于我放置 GETDATE() 的位置


FeatureNotSupported: ROW expression, implicit or explicit, is not supported in target list

【问题讨论】:

    标签: python amazon-redshift getdate


    【解决方案1】:

    “INSERT ... VALUES (...)”构造用于将文字插入表中,而 getdate() 不是文字。但是,有多种方法可以使其发挥作用。几个简单的方法是:

    1. 您可以将“time_”列的默认值设置为 getdate(),然后在 insert values 语句中使用键 work default。这将告诉 Redshift 使用列的默认值 (getdate())

      插入值('A','B',3,默认值)

    2. 您可以切换到“INSERT ... SELECT ...”结构,这将允许您混合使用文字和函数调用。

      插入表(选择“A”、“B”、3、getdate())

      注意:如果插入的行数很大,在 Redshift 中逐行插入表可能会减慢速度并弄乱表。如果自动提交开启,这可能会更加复杂,因为每个插入都将被提交,这将需要通过提交队列。如果您要插入大量数据,您应该通过编写 S3 对象并将其复制到 Redshift 来执行此操作。或者至少将 100 多行数据捆绑到一个插入语句中(关闭自动提交并在末尾显式提交更改)。

    【讨论】:

    • 创建表 my_table (id int, created_at datetime default sysdate); stackoverflow.com/questions/34587051/…
    • 谢谢你。问题 - 我是否从这部分删除 getdate() values_ = ', '.join([f"('{str(i.columnA)}','{str(i.columnB)}','{str(i .columnC)}','{str(i.columnD)}', 'GETDATE()')" for i in df2.itertuples()]) ?
    • 是并添加关键字 default per - docs.aws.amazon.com/redshift/latest/dg/…
    • 像这样? vals=', '.join([f"('{str(i.columnA)}','{str(i.columnA)}','{str(i.columnA)}','{str(i .column)}',在 df2.itertuples()] 中为 i 默认为 'GETDATE()')"
    • 不。只是值字符串中的默认值。 getdate() 进入表的表定义 - 在 CREATE TABLE 语句中。如果您无法重新定义表格(只需要完成一次),那么您需要在我的回答中选择选项 #2。
    【解决方案2】:

    当我创建表时,我使用时间戳添加了一个 time_log 列。

    drop table if exists table1;
    create table table1(
    column1 varchar (255),
    column2 varchar(255),
    time_log timestamp
    );
    

    问题是我在插入语句中的值周围有括号。删除那些,它将起作用。{values_}

    sqlexecute(f'''insert into table.table2 (columnA, columnB, time_log) 
                values
        ({values_})  
        ;
        ''')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多