存在时的情况 - 列(SQL)

时间:2017-07-19 13:49:10

标签: postgresql psql

我正在尝试使用'0'填充XML文件的字段,如果特定列(pv_an4)不存在,或者使用列的值(如果存在)填充。

到目前为止,这是我的代码:

....

when exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'phonebook' AND COLUMN_NAME = 'pv_an4') then 'pv_an4 exists'
end ),

....

当我执行此操作时,我收到此错误:

  

FEHLER:专栏»pv_an4«不存在ZEILE 25:...... E_NAME =   'phonebook'AND COLUMN_NAME ='pv_an4'),然后是pv_an4

但这对我来说没有任何意义,因为例如使用这段代码它会起作用:

    SELECT
XMLFOREST( xmlpb.entry as "DivinusIPPhoneDirectory" )
FROM (
SELECT
XMLCONCAT (
XMLELEMENT ( NAME "Title", 'Phonelist' ),
XMLELEMENT ( NAME "Prompt", 'Prompt' ),
XMLAGG (
XMLELEMENT (
NAME "DirectoryEntry",
XMLELEMENT( Name "Name",
case
when (pb.company = '') IS FALSE AND pb.lastname != '' and pb.firstname != '' then pb.company || ' - ' || pb.lastname || ', ' || pb.firstname
when (pb.company = '') IS FALSE AND pb.lastname != '' and pb.firstname = '' then pb.company || ' - ' || pb.lastname
when (pb.company = '') IS FALSE AND pb.lastname = '' and pb.firstname = '' then pb.company
when (pb.company = '') IS FALSE AND pb.lastname = '' and pb.firstname != '' then pb.company || ' - ' || pb.firstname
when (pb.company = '') IS NOT FALSE AND pb.lastname != '' and pb.firstname != '' then pb.lastname || ', ' || pb.firstname
when (pb.company = '') IS NOT FALSE AND  pb.lastname != '' and pb.firstname = '' then pb.lastname
end ),
XMLELEMENT( Name "Telephone", pb.pv_an3 ),
XMLELEMENT( Name "Telephone",
case
when not exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'phonebook' AND COLUMN_NAME = 'pv_an4') then ''
else pb.pv_an4
end ),
XMLELEMENT( Name "Telephone", pb.phonenumber ),
XMLELEMENT( Name "Telephone", pb.pv_an1 ),
XMLELEMENT( Name "Telephone", pb.pv_an2 )
)
)
) as entry
FROM
phonebook pb
WHERE fkidtenant = 1

我花了一整天时间试图解决这个问题,有人可能会向我提示正确的方向吗?

/ edit:完整查询如下:

<Switch>
    <Route exact path='/roster' component={FullRoster}/>
    <Route path='/roster/:number' component={Player}/>
</Switch>

2 个答案:

答案 0 :(得分:2)

整个sql语句在运行之前解析并编译,因此postgresql会抱怨缺少的字段。没有捷径。

如果要处理此类场景,则需要使用动态生成的sql(检查列是否存在并创建相应的sql语句)。虽然我无法想象为什么你不应该知道表中是否存在某个列。

答案 1 :(得分:0)

尝试:

XMLELEMENT( Name "Telephone",
case
when not exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME   = 'phonebook' AND COLUMN_NAME = 'pv_an4') then ''
when exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'phonebook' AND COLUMN_NAME = 'pv_an4') then 'pv_an4'
end ),

在第4行中,您在第一个查询中使用pv_an4作为列,但在第二个查询中使用pv_an4作为列值。