SELECT WITH STRING FORMATTING

Asked

Viewed 814 times

0

Using the Mysql Database, intending to perform the query in a given table whose one of its fields data has as type VARCHAR(8).

Query SQL - Current

SELECT `t_movimentacao`.`data` FROM t_movimentacao 
WHERE `t_movimentacao`.`id` = '1';

Running the current query we get the following return: 23072019

|   data   |
- 23072019 -

Knowing that the string contains a date in the format dd/mm/yyyy, without the character of / how we can format and customize this field directly in the same query.

I want an SQL Query - Formatting the date field to obey the second result in the query: 23/07/2019

|    data    |
- 23/07/2019 -

How to format the string to place the / and receive the date in the desired format directly in SQL?

3 answers

4

If you don’t need to work with DATA, only for formatting and presentation from sql you can use the function CONCAT and SUBSTR. The function CONCAT concatenates one or more parameters and the SUBSTR function extracts a substring from a string by passing the string the start you want to start and how many characters. If you need to, I believe you will have q convert the string to date and consider mysql configuration.

SELECT
  CONCAT(SUBSTR(t_movimentacao.data, 1, 2), "/", SUBSTR(t_movimentacao.data, 3, 2), "/", SUBSTR(t_movimentacao.data, 5, 4))
FROM t_movimentacao
WHERE t_movimentacao.id = '1';
  • Thank you very much friend, it worked perfectly! I knew that SQL has advanced query functionalities although I do not know them. I thank you for the soliciting spirit of all who have helped me here to solve the problem. Thank you.

1

SELECT cast(left(data,2) as nvarchar) + '-' + SUBSTRING(data,3,2) + '-' + 
cast(RIGHT(data,4) as nvarchar) as data FROM t_movimentacao 
WHERE id = 1;

0

SELECT DATE_FORMAT(`t_movimentacao`.`data`, '%d / %m / %y') FROM t_movimentacao 
WHERE `t_movimentacao`.`id` = '1';

see if it goes like this

  • Unfortunately the value returned null.

  • Try changing the uppercase letter, or something because the bank is Case Sensitive.

  • this DATE_FORMAT works with an expected date already, what can be done is another select in returning in the first select and using after

  • This tip should work even if the field is vachar? unfortunately I’m not succeeding here.

  • I can get some results using this format(`t_movimentacao`.`11_data_de_movimentacao`, '%d/%m/%yyyy') and as a result I receive the date in this format: 2,372,019.

  • WARNING, it will not be useful to use the DATE_FORMAT function because the field is not of type DATE, it is of type VARCHAR, that is, DATE_FORMAT will not understand as if the value was date.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.