Reputation: 86855
How can I set the datatype of columns in a mysql
view
?
The following is incorrect:
CREATE VIEW person_view AS
SELECT 'Test' AS VARCHAR(20) person_firstname,
person.age AS int(2) person_age
FROM person;
table person:
#firstname, lastname, age
john, doe, 8
jane, doe, 5
The example data will trigger the generation of VARCHAR(4)
for firstname and int(1)
for age. But in fact I want to support VARCHAR(20)
and int(2)
for those columns in the view.
Upvotes: 3
Views: 6520
Reputation: 522346
A view just sits on top of the underlying table against which it was defined, so views normally do not allow us to change the table definition. If, for example, you wanted to create a view which consisted only of the first 20 characters of some potentially larger varchar
column, you could do so using LEFT
, e.g.
CREATE VIEW yourView AS (
SELECT LEFT(some_col, 20) AS some_col_short
FROM mysource
)
But even here, we are not changing the definition of the table, only the way the underlying data is being viewed.
Upvotes: 1
Reputation: 1767
Try using CAST or CONVERT
CREATE VIEW myview AS SELECT CAST('Test' AS VARCHAR(20)) Column1 FROM mysource;
Upvotes: 3