用零填充文本字段

问题描述 投票:-1回答:2

我有一个postgres数据库,我可以使用PGAdmin III访问。我运行一个脚本来更改存储在文本字段中的数字,然后添加左边的零以将其归档为四个字符。这是一个必须存储为文本的时间字段。我想在一次运行中而不是两次运行。这是将时间字段作为文本添加小时的第一个子句;

UPDATE timetable
SET eta = (
  CASE 
    WHEN (trips.starttime::int / 100) + (destination.zuluoffset * -1 ) < 24 THEN ((trips.starttime::int / 100) + (destination.zuluoffset * -1 )) * 100
    WHEN (trips.starttime::int / 100) + (destination.zuluoffset * -1 ) > 23 THEN ((trips.starttime::int / 100) + (destination.zuluoffset * -1 ) - 24) * 100
  END )
FROM  
  destination, 
  trips
WHERE 
  timetable.tripsid = trips.id;

这样做很好,并且在校正大于24小时的结果时增加了所需的小时数。但是,这样的任何时间都会少于1000个小时,因为三个数字甚至是午夜的0个小时。该字段需要4个字符。

所以我把它作为第二个条款;

UPDATE timetable
SET eta = lpad(eta, 4, '0');

这也有效。但是如何将lpad添加到第一个Update子句中呢?我尝试将整个CASE语句放在lpad语句中代替eta,就像这样;

SET eta = lpad((CASE statement here), 4, '0')

但是我得到了这个错误;

ERROR:  function lpad(numeric, integer, unknown) does not exist
LINE 3: SET eta = lpad((
                  ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts. 

我已经尝试使用:: int,:: text和:: varchar转换eta,但这只是返回一个sytax错误。

sql postgresql sql-update
2个回答
1
投票

如果CASE语句的结果是数字,为什么使用LPAD,只使用to_char:

 UPDATE timetable
          SET eta = to_char (
               CASE 
                 WHEN (trips.starttime::int / 100) + (destination.zuluoffset * -1 ) < 24 THEN ((trips.starttime::int / 100) + (destination.zuluoffset * -1 )) * 100
                WHEN (trips.starttime::int / 100) + (destination.zuluoffset * -1 ) > 23 THEN ((trips.starttime::int / 100) + (destination.zuluoffset * -1 ) - 24) * 100
            END , 'FM0000')
FROM  destination
INNER JOIN trips ON timetable.tripsid = trips.id;

1
投票

应该是LPAD(your_col::text, 4, '0')

    UPDATE timetable
    SET eta = LPAD ((
      CASE 
        WHEN (trips.starttime::int / 100) + (destination.zuluoffset * -1 ) < 24 THEN ((trips.starttime::int / 100) + (destination.zuluoffset * -1 )) * 100
        WHEN (trips.starttime::int / 100) + (destination.zuluoffset * -1 ) > 23 THEN ((trips.starttime::int / 100) + (destination.zuluoffset * -1 ) - 24) * 100
      END )::text, 4,'0')
    FROM  destination
    INNER JOIN trips ON timetable.tripsid = trips.id;
© www.soinside.com 2019 - 2024. All rights reserved.