Thread: text -> char

text -> char

From
Peter Stamfest
Date:
I want to extract portions of a TEXT column into a CHAR(8) column:

> create table one (descr text);
> create view  two as select substr(descr, 2, 4) as d from one;
> \d two
View    = two
Query   = SELECT "substr"("one"."descr", '2'::"int4", '4'::"int4") AS
"d" FROM "one";
+-----------------------+------------------------------+-------+
|      Field            |          Type                | Length|
+-----------------------+------------------------------+-------+
| d                     | text                         |   var |
+-----------------------+------------------------------+-------+

> create view three as select CAST(substr(descr, 2, 4) as char(8)) as
d from one;
> \d three
View    = three
Query   = SELECT "substr"("one"."descr", '2'::"int4", '4'::"int4") AS
"d" FROM "one";
+-----------------------+------------------------------+-------+
|      Field            |          Type                | Length|
+-----------------------+------------------------------+-------+
| d                     | text                         |   var |
+-----------------------+------------------------------+-------+

SELECT INTO behaves the same way. It seems impossible to cast a TEXT into
a CHAR.

The char() function works neither:

> create view four as select char(substr(descr, 2, 4)) as d from one;
ERROR:  parser: parse error at or near "substr"

Any ideas?
This is 6.5.2 (RH Linux 6.1)

Thanks in advance

peter




Re: [SQL] text -> char

From
Tom Lane
Date:
Peter Stamfest <peter.stamfest@eunet.at> wrote a couple weeks ago:
> create view three as select CAST(substr(descr, 2, 4) as char(8)) as
> d from one;

That should work, and as of today it does work in current sources:

regression=# create view three as select CAST(substr(descr, 2, 4) as char(8))
regression-# as d from one;
CREATE 278003 1
regression=# \d three         View "three"Attribute |  Type   | Modifier
-----------+---------+----------d         | char(8) |
View definition: SELECT (substr(one.descr, 2, 4))::char(8) AS d FROM one;

Releases before 7.0 had a tendency to just discard casts :-( in a lot
of corner cases, and this is one of 'em.  I've cleaned up the cast
problems I know about, but there may be some left...

> The char() function works neither:
> create view four as select char(substr(descr, 2, 4)) as d from one;
> ERROR:  parser: parse error at or near "substr"

That's not a bug.  CHAR is an SQL reserved word for a type --- the
parser is expecting a type length indicator, like "char(8)", when it
sees CHAR(.

While there is a function named "char", you can only get at it by
double-quoting the name so it no longer looks like a keyword:

select "char"(substr(descr, 2, 4)) as d from one;

Also note that this converts to the internal single-byte char type,
which is presumably not what you wanted anyway.
        regards, tom lane