【问题标题】:Postgres usage of format()Postgres 对 format() 的使用
【发布时间】:2017-01-05 09:05:59
【问题描述】:

在这种情况下使用 format() 通常可以互换吗?

exec_str := format('UPDATE ' || TG_ARGV[0] || 
                    ' SET username = current_user,
                              time = current_timestamp::timestamp(0);'
                  );
EXECUTE exec_str;

对比

exec_str := 'UPDATE ' || TG_ARGV[0] || 
                    ' SET username = current_user,
                              time = current_timestamp::timestamp(0);'
                  ;
EXECUTE format(exec_str);

【问题讨论】:

  • 你都试过了吗?
  • 是的,两者都有效。我只是想知道其中一种变体是否会产生错误。到目前为止,我没有任何问题。安全总比后悔好;)

标签: sql postgresql format plpgsql


【解决方案1】:

函数format()的主要好处是可以使用参数:

execute format('
    UPDATE %I 
    SET username = current_user,
        time = current_timestamp::timestamp(0);',
    TG_ARGV[0]);

the documentation阅读更多内容。

【讨论】:

  • 使用EXECUTE ... USING ... 不是更好吗?
  • @LaurenzAlbe USING 只能绑定值,不能绑定标识符(就像在原始问题中一样)。
猜你喜欢
  • 2012-12-13
  • 2016-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多