简体   繁体   中英

How to query date with a column name in SQL?

how do I query just the date and not the time from the stored data? I have tried the following:

select FirstName, dob from table1 where rno='123';

What I require is dob returns just the date along with a column name, so I can use the value later in ac# .net project. Also, is it possible to change the format of the date? How do I customize it to DD-MM-YYYY or YYYY-MM-DD ?

Look at DATE_FORMAT

So try

select FirstName, DATE_FORMAT(dob, '%d-%m-%Y') as dob from table1 where rno='123';

The best way to handle this is to return the full and unformatted datetime value , and let your C# code worry about formatting it and showing only the date.

In other words, don't change the SQL in the question at all.

This will save work for the database (and therefore improve scalability), while also making it easier for your app to adapt automatically to the preferred format of your users. So a user in the UK may see dd/MM/yyyy , while a user in the US could see MM/dd/yyyy from the same code.

How exactly this works depends greatly on the context of your app, and that information is not in the question, but it boils down to making sure the CultureInfo of the current process is correct (ie: supplied by the current culture settings in Windows or inferred by ASP.Net from the browser user-agent and request headers), and then formatting using the short date string standard datetime format string .

But if you really want to do this in the database, you can use the FORMAT() function, and name the result using the AS keyword so you can reference it in later code:

SELECT FORMAT(dob, 'dd/MM/yyyy') AS dob FROM table1 WHERE rno='123';

or

SELECT FORMAT(dob, 'yyyy-MM-dd') AS dob FROM table1 WHERE rno='123';

At this point, the C# will receive a string instead of DateTime value. Again, it's very much a good idea to let the database return the DateTime value and have the C# code worry about getting the right string representation when you need it.

If you want to remove the time for privacy issues (which I don't think is the case), you can cast it to DATE.

select FirstName, CAST(dob as DATE) AS dob from table1 where rno='123';

If not, I would take the date as-is from SQL to C#, and only do the formatting in the View. Avoid DATE_FORMAT and converting to string. This way, you can:

  1. Do date manipulation: eg date add

  2. Do date comparison or calculation: eg older than x?

  3. Sort

  4. Convert to users' local format.

    etc.

If you convert it to string in SQL, in most instances, you will end up converting it back to DateTime class from the string, if not right now, in 5 years when the scope of your project increases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM