使用 format() 多次使用相同参数的动态查询

Zer*_*uno 2 sql database postgresql dynamic-sql plpgsql

我有一个过程,它将表名称的后缀作为输入。然后,使用execute format(),我传递此参数来执行动态查询。问题是这个参数始终是相同的 - 我不想像这样传递它 x 次:

execute format('SELECT table_%s.field1, table_%s.field2,table_%s.field3
FROM table_%s', inTableSuffix, inTableSuffix, inTableSuffix, inTableSuffix, ...) 
Run Code Online (Sandbox Code Playgroud)

我想要类似于以下的格式:

execute format('SELECT table_%s.field1, table_%s.field2,table_%s.field3
FROM table_%s', inTableSuffix) 
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用表名的别名来解决这个问题,但是还有其他选择吗?

wil*_*ser 6

您可以像这样重复处理位置参数:


execute format('SELECT table_%1$s.field1
   , table_%1$s.field2,table_%1$s.field3
FROM table_%1$s;', inTableSuffix); 
Run Code Online (Sandbox Code Playgroud)

注意:在这种特殊情况下,您可以使用别名来避免重复:


execute format('SELECT tx.field1
   , tx.field2, tx.field3
FROM table_%s tx;', inTableSuffix); 
Run Code Online (Sandbox Code Playgroud)