Insert "/" into a SQL column to format it for date

1

A client sent me their database in which dates are included, however they come with a YYYYMMDD format, and I would like to create a "query" where I can insert the "/" delimiter in that column so that it remains this way YYYY/MM/DD .

    
asked by Jorge_55 17.03.2017 в 02:13
source

1 answer

0
  

I would like to create a "query" where I can insert in that column the   delimiter "/" so that it looks like this YYYY / MM / DD

What you intend to do is a Error.

A database stores data and even if it could, it does not exist to store formats or formatted data .

If you store a formatted data, it does not work for you except for that use for which you formatted it. Nor is it useful to make calculations with him. Suppose you want to present that date in another format, or you want to calculate the difference between two columns in your table. If you modify it by adding /, they are simply spoiling your data.

In the database the columns of the date type should be stored as they are. and when it's your turn to present its content then you give it the format you want, but the data will always be kept like this: YYYYMMDD. (Sometimes they carry the time too, but it is not mandatory).

All BD handlers have instructions to present our data the way we want. Look, for the example MySQL case .

I leave you an example of a field of the date type, stored as YYYYMMDD and you will see in the example three ways to present the same data . But if formatting at the origin is already impossible, that flexibility is lost.

SQL Fiddle

MySQL 5.6 Schema Setup :

CREATE TABLE IF NOT EXISTS Tabla (
    'nombre' varchar(70),  'fecha_nacimiento' date  
);


INSERT INTO Tabla
    ('nombre',  'fecha_nacimiento')
VALUES
    ('Pedro','20000120'),
    ('Santiago','19990318'),
    ('Juan','19720822')
;

Query 1 :

SELECT 
   nombre,    
   DATE_FORMAT(fecha_nacimiento,'%Y%m%d') AS COMO_ES ,
   DATE_FORMAT(fecha_nacimiento,'%d/%m/%Y') AS DD_MM_YY ,
   DATE_FORMAT(fecha_nacimiento,'%Y/%m/%d') AS YYYY_MM_AA, 
   DATE_FORMAT(fecha_nacimiento,'%W %M %Y') AS UNO_LARGO 
FROM Tabla

Results :

|   nombre |  COMO_ES |   DD_MM_YY | YYYY_MM_AA |             UNO_LARGO |
|----------|----------|------------|------------|-----------------------|
|    Pedro | 20000120 | 20/01/2000 | 2000/01/20 | Thursday January 2000 |
| Santiago | 19990318 | 18/03/1999 | 1999/03/18 |   Thursday March 1999 |
|     Juan | 19720822 | 22/08/1972 | 1972/08/22 |   Tuesday August 1972 |
    
answered by 19.03.2017 в 06:25