【问题标题】:Use variables in side insert or update query in postgres在 postgres 中使用侧面插入或更新查询中的变量
【发布时间】:2020-12-03 09:07:45
【问题描述】:

我正在编写 sql 脚本,只有当表中缺少记录时,我才需要在数据库中插入记录,如果表中确实存在记录,我需要更新 template 这是我的 sql 查询

insert into deployment.nodes values('sind','11', now(),'temp',
   '<table id="producttable">
 <thead>
    <tr>
  <td>UPC_Code</td>
  <td>Product_Name</td>
  </tr>
  </thead>
 <tbody>
   <!-- existing data could optionally be included here -->
 </tbody>
</table>

<template id="productrow">
<tr>
 <td class="record"></td>
   <td></td>
 </tr>
 </template> ')  on conflict on constraint nodes_pkey 
DO UPDATE SET latest=now(), status='active',
agent='<table id="producttable">
<thead>
<tr>
  <td>UPC_Code</td>
  <td>Product_Name</td>
  </tr>
  </thead>
<tbody>
 <!-- existing data could optionally be included here -->
 </tbody>
</table>
<template id="productrow">
  <tr>
   <td class="record"></td>
     <td></td>
    </tr>
 </template>'

这个 sql 脚本对我来说运行良好,但我想在变量中使用 HTML 的东西来最小化 sql 脚本的长度。

让我们说

var template = '<html> ....  </html>'  and then query will be like 
insert into deployment.nodes values('sind','11', now(),'temp',template)  on conflict on constraint 
nodes_pkey   DO UPDATE SET latest=now(), status='active',agent=template

【问题讨论】:

  • 你可以把它作为返回值存储在一个函数中吗?
  • @VynlJunkie 任何提示如何获得这些?
  • set agent = EXCLUDED.agent 见这里:postgresql.org/docs/current/sql-insert.html
  • @MikeOrganek 无法从墨迹中理解,请您举个小例子

标签: sql postgresql sql-insert


【解决方案1】:

EXCLUDED 伪表使用示例:

insert into deployment.nodes values('sind','11', now(),'temp',
   '<table id="producttable">
 <thead>
    <tr>
  <td>UPC_Code</td>
  <td>Product_Name</td>
  </tr>
  </thead>
 <tbody>
   <!-- existing data could optionally be included here -->
 </tbody>
</table>

<template id="productrow">
<tr>
 <td class="record"></td>
   <td></td>
 </tr>
 </template> ')  on conflict on constraint nodes_pkey 
DO UPDATE 
  SET latest = EXCLUDED.latest, 
      status = EXCLUDED.status,
      agent = EXCLUDED.agent

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 2011-12-16
    • 2021-06-01
    • 2018-12-13
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多