tags:

views:

33

answers:

1

I have a view that contains a calculated column. Is there are a way to cast it as a CHAR or VARCHAR rather than a VARBINARY ? Obviously, I have tried using CAST(... as CHAR) but it gives an error.

Here is a simple replicable example.

CREATE VIEW view_example AS 
SELECT concat_ws('_', lpad(9, 3,'0'), lpad(1,3,'0'), date_format(now(),'%Y%m%d%H%i%S'))
AS calculated_field_id;

This is how my view is created:

describe view_example;
+---------------------+---------------+------+-----+---------+-------+
| Field               | Type          | Null | Key | Default | Extra |
+---------------------+---------------+------+-----+---------+-------+
| calculated_field_id | varbinary(27) | YES  |     | NULL    |       |
+---------------------+---------------+------+-----+---------+-------+

 select version();
+-----------------------+
| version()             |
+-----------------------+
| 5.0.51a-community-log |
+-----------------------+
A: 

CREATE VIEW view_example AS SELECT CAST(""+concat_ws('_', lpad(9, 3,'0'), lpad(1,3,'0'), date_format(now(),'%Y%m%d%H%i%S')) AS CHAR) AS calculated_field_id;

I have no idea why. If you leave off the cast, it becomes a double. MySQL: a laugh a minute.

barrycarter
Thanks Barry. I removed '""+' from your solution and it worked for me fine. (With the empty quote included I was only getting the first character returned.)CREATE VIEW view_example AS SELECT CAST(concat_ws('_', lpad(9, 3,'0'), lpad(1,3,'0'), date_format(now(),'%Y%m%d%H%i%S')) AS CHAR) AS calculated_field_id;
Chris Brent
Weird. I thought you said CAST gave you an error. I thought adding the empty string might obviate that error.
barrycarter
It looks like CAST gave an error because I was using CAST(... AS VARCHAR) - it turns out I needed CAST(... AS CHAR) . As it happens this defines the field as VARCHAR.
Chris Brent