Recently, when doing a project, there is a need to find out the current logged in the user's jurisdiction over all areas of the data, and the query of the Department information in the following format to show
Supreme People's Court > Jiangsu Provincial Higher courts > Nantong Intermediate Court
Supreme People's Court > Jiangsu Provincial Higher courts > Lianyungang Intermediate Court
, then query with the following statement
WITH RECURSIVE T AS (
SELECT
c_id,
c_name
FROM
db_aty.t_aty_corp
WHERE
c_pid IS NULL
UNION ALL
SELECT
D.c_id,
T.c_name || ‘>‘ || D.c_name
FROM
db_aty.t_aty_corp D
JOIN T ON D.c_pid = T .c_id
) SELECT
c_id AS corpId,
c_name AS corpName
FROM
T
However, the following error occurred
error:recursive query "T" column 2 has type character varying ($) in non-recursive term but type character varying over All
Guess this is because the use of union ALL in an SQL statement requires the same field properties that are queried before and after the query, using T.c_name | | ' > ' | | D.c_name is a concatenation of strings, so the field properties are associated with the previous
C_name inconsistent, so cause error,
Workaround: Specify the field format for the stitched string
WITH RECURSIVE T AS (
SELECT
c_id,
c_name::varchar(150)
FROM
db_aty.t_aty_corp
WHERE
c_pid is null
UNION ALL
SELECT
D.c_id,
(T.c_name || ‘>‘ || D.c_name )::varchar(150) as c_name
FROM
db_aty.t_aty_corp D
JOIN T ON D.c_pid = T .c_id
)
SELECT c_id AS corpId ,c_name as corpName FROM T
Get the correct answer as follows
PostgreSQL error:recursive Query "T" column 2 has type character varying ($) in non-recursive term but type character VA Rying overall