remove time from sql - sql

Please can any ove suggest me how i can remove time part from sql dates. I have already read 100s of articles and most of them remove the time but leaves 00:00:00 behine which i don't want also i know that i can remove these ZERO's by doing a convert to varchar but unfortunately i cannot change the type of the date column it has to be date type instead of string
Please advise
Thanks

A datetime column in the database will always contain both a date portion and a time portion. SQL Server 2008 introduces types that store only date or only time. But, so long as the column is of type datetime, you'll have to accept that the time portion exists, and you can just ignore it in your application (by applying suitable formatting).
You can add a check constraint to the table to ensure that all entries in the column always have the same time portion (e.g. 00:00:00).

You need to apply a format string to your gridview column to only display the date part. An example of such a string would be dd MMMM yyyy
Is this an ASP.NET gridview? If so there is example code here.

A SQL server DateTime type is a date and a time in SQL 2005 there is no date only field type, you cannot remove the time component and still have a field that is a DateTime type. Your options are the ones you have outlined: Convert to (n)varchar and remove the time componenet, leave it as a DateTime and accept that it has a time component. Why do you wish to remove the time component, what problem would this solve for you.
Further to your comment below, the database is not where you should be formating you Date strings to display in your GridView. You do display layer things in the display layer, in this case in the gridview. You need to use a format string in your data when data binding to the gridview. Yee examples below.
BoundField:
<columns>
<asp:BoundField headertext="CreationDate" dataformatstring="{0:dd-MM-yyyy}" //rearrange these letters as necessary
datafield="CreationDate" />
</columns>
TemplateField
<itemtemplate>
<asp:Label id="Label1" runat="server" Text='<%# Bind("CreationDate", "{0:M-dd-yyyy}") %>'>
</asp:Label>
</itemtemplate>

Try this
select cast(convert(char(11), getdate(), 113) as datetime)

SELECT convert(varchar, getdate(), 101)
OR
Declare #datetime datetime
set #datetime = getdate()
SELECT convert(varchar, #datetime, 101)
DateTime Formats
EDIT:
SQL server 2008 has this
functionality, if you can upgrade.
Just make sure to save 00:00:00 in
your table and remove time part in
Return datetime and format it in your
grid or in your code.

If you could upgrade to SQL2008, that has a separate time command.
I see you say you want to keep it as a datetime object, so as far as I can see if you can't upgrade to 2008 then you are stuck with the zeros

You can't remove time part from thr datetime datatype field.
Only thing you can do is to cast it to the date or varchar datatype before output or to set time part to 00:00:00 before insert/update.
Example:
the statement:
select cast(getdate() as date)
returns only date

What are you trying to do?
Why do you care if the database is saving the exact time or 00:00:00?
When you query this field(inside or outside the DB) you can ignore the time value and show only the date...
Again, say what you are trying to do... I believe it will be easier to help you.

Update mytable set mydatetime=convert(datetime,convert(char(10),mydatetime,103),103)
This will update your table. Hope that is what your looking for.
103: Format datetime as dd/mm/yyyy.

Related

Convert YYYYMMDD to MM/DD/YYYY in Snowflake

I need help in figuring out the date conversion logic in Snowflake. The documentation isn't clear enough on this.
In SQL Server, I would try
SELECT CONVERT(DATE, '20200730', 101)
and it gives me '07/30/2020'.
If I try the following in Snowflake,
to_varchar('20200730'::date, 'mm/dd/yyyy')
it gives me '08/22/1970'. Why would it give an entire different date? Need help in getting the logic with the correct date.
The issue with what you are doing is that you are assuming that Snowflake is converting your string of '20200730'::DATE to 2020-07-03. It's not. You need to specify your input format of a date. So, 2 options based on your question being a bit vague:
If you have a string in a table and you wish to transform that into a date and then present it back as a formatted string:
SELECT TO_VARCHAR(TO_DATE('20200730','YYYYMMDD'),'MM/DD/YYYY');
--07/30/2020
If the field in the table is already a date, then you just need to apply the TO_VARCHAR() piece directly against that field.
Unlike SQL Server, Snowflake stores date fields in the same format regardless of what you provide it. You need to use the TO_VARCHAR in order to format that date in a different way...or ALTER SESSION SET DATE_OUTPUT_FORMAT will also work.
Try select to_varchar(TO_DATE( '20200730', 'YYYYMMDD' ), 'MM/DD/YYYY'); which produces 2020-07-30
You may need to refer to https://docs.snowflake.com/en/user-guide/date-time-input-output.html#timestamp-formats

Setting Date Format for multiple date columns in SSRS

I have over 65 columns among which there are about 30 Date Columnns. I want to set it to MM/DD/YYYY. Presently it is also showing the time YYYY-MM-DD hh:mm:ss. I tried correcting this within the SQL query by using cast. The SQL output shows only date, but it again gets represented in DateTime in SSRS. I dont want to right click on 30 columns manually to set date format. Is there a way to set default date format for all date columns in the report?
"Cast" is not helping here since it is about types, not format.
Try using the "convert" function instead.
In your case, it would be
-- use your field name instead of sysdatetime()
select convert(varchar, sysdatetime(), 101/*mm/dd/yyyy format Id*/);
You should be able to select all the fields in the tablix and change the formatting together. You may wish to consider using a parameter for the formatting.

Update table Error Using Convert Function In SQL Server 2005

I have a table with two columns, all of them are datetime value
Such as, Column A with value ‘07/09/2012 14:13:34’
Now, I want to update column A to yyyymmdd by statement
Update Change_Date
SET A = CONVERT(VARCHAR(8),A,112)
It shows succsessful message but with no effect (no update value to 20120907) in my table Change_Date.
Any help will be greated, thank you!
A datetime fields saves a date time. How you see that date time is a result of the tool you're using to inspect the data, whether it is Management Studio, or your own software that's printing something from the database.
I strongly recommend keeping it as a datetime field. This will allow you to do date-related operations, such as subtractions and comparisons. If you want to change how your users see the date, then format your date at the presentation layer.
What's happening in the code you've posted is that you're setting the value of A to the same date that it already is. The fact that you're setting that value by means of a string in another format has no relation, SQL server will always have to parse your string input into a date that it can understand. This is why you're not getting an error message. The operation is working, only it's not changing anything.
You can select the date column in specified format or make a view which selects the column value in yyyymmdd format:
SELECT CONVERT(VARCHAR(8), A, 112) FROM Change_Date
It's because the datatype of the column is DATE or DATETIME and it has specific format. If you want to update the column with specific format, make another column and make its datatype VARCHAR. I believe 112 is yyyymmdd format.
I strongly suggest that you keep it AS IS. Database is the storage of data and not for viewing purposes. It is easy to perform task for dates if your data type is DATETIME or DATE. If for instance you want to retrieve the dates with specific format, that's the time you convert your date.
Hope this makes sense.

How do I store just a date in MS SQL from VB?

My project requires I use VB (5 or 6)* to store a date in an SQL Server database. The SQL datetime type includes the time, which I don't want. I'm also aware that VB's representation of a date doesn't mirror that of SQL Server.
So, how can I store a date held in VB's date type in the SQL database, as the datetime at midnight on that date, for example?
Edit: I need to use the date to select rows further down the line, so I can't get away with just truncating it on read.
*I know, I you were me, you wouldn't start from here. But given the constraints, any VB6/MS SQL fiends out there?
VB6 has a DateValue() function which returns the date portion of a Date/Time value, with the time portion "zeroed out". (Note: When the time portion of a date/time variable is "zeroed out", the time would be interpreted as 12:00 AM.)
SQL Server 2008 has new date and time data types. There is the "Date" data type if you don't want to store the time component.
Use the DateTime column and just truncate the time at the presentation level.
Try inserting and updating the date like this:
CAST(FLOOR(CAST(#DateTime AS float)) AS datetime)
We have this in a UDF and it basically strips the time part from a datetime.
In VB you can use the Date() function to return the current date with no time element.
If you an use an ADO Parameter object with a Command object then the OLE DB provider should handle the conversion of a VB Date type to the SQL Server DATETIME value.
In SQL Server (pre SQL 2008 DATE type) you should create a CHECK constraint on the column to ensure it is not possible to add a date with a time element (note I've used an unambiguous language 'safe' format for my DATETIME literals) e.g.
ALTER TABLE MyTable ADD
vb_date DATETIME NOT NULL
CONSTRAINT vb_date__no_time_element
CHECK ((vb_date = DATEADD(DAY, DATEDIFF(DAY, '1990-01-01T00:00:00.000', vb_date), '1990-01-01T00:00:00.000')));
I would just use DateSerial to create the date you need. You pass it a year, month and day and it gives you a date with midnight as the time. You can then use it to pass as a parameter to an ADO command or similar. When you read it, it will have midnight so that isn't a problem. I like it better than DateValue as there is no string conversion. If you really want you can create your own function like DateValue that uses DateSerial.
Function JustTheDatePlease(ByVal dtSource As Date) As Date
JustTheDatePlease = DateSerial(Year(dtSource), Month(dtSource), Day(dtSource))
End Function
If for some reason you aren't using parameterized queries, and you really should have a good excuse for this, you can use the ODBC canonical form of a date in your queries. You just format the date as {d 'yyyy-mm-dd'} for example {d '2009-04-06'}.

SQL date format issue in select query

I have an ASP page which will fetch records from a SQL server DB table. The table "order_master" has a field called order_date. I want to frame a select query to fetch order date > a date entered by user(ex : 07/01/2008)
I tried with convert and cast, but both are not working. The sample data in order_date column is 4/10/2008 8:27:41 PM. Actually, I dont know what type it is (varchar/datetime).
Is there any way to do that?
I'd check to make sure that the SQL datatype is a DateTime or SmallDateTime first, then I'd check to make sure that you're passing in a Date/DateTime value from the page.
If those are both correct, then you'd probably be better off following Joel's advice and explicitly convert both values to dates before trying the comparison. Also, check the precision of the time values that you're looking at; it seems obvious, but 1/1/2008 12:00:00.001 AM will not be equal to 1/1/2008 12:00:00.000 AM. Yes, I am speaking from experience. :P
the 07/01/2008 date is the British/French annotation, so all you need to do is:
SELECT myColumn FROM myTable WHERE myDateField >= convert(datetime, '07/01/2008 00:00:00', 103)
this code will get all rows where myDateField has the date 7th of January 2008, since 00:00:00 (hh:mm:ss) so, the first second on that day... in simple words, the entire day.
for more info, check Books online on MSDN
You could create a stored procedure like this
CREATE PROCEDURE GetOrders
#OrderDate DATETIME
AS
SELECT
*
FROM order_master
WHERE Order_Date > #OrderDate
GO
Then you can just convert the users input to a date before calling the stored procedure via your ASP code.
Edit
I just noticed the remark about the column type, you can run this command
sp_help order_master
to get column information to find the data type of order_date.
Have you tried CONVERT()'ing both values to a datetime type?
Remember that when comparing dates, 4/10/2008 8:27:41 PM is not equal to 4/10/2008. SQL Server will interpret 4/10/2008 to mean 4/10/2008 12:00:00 AM, and do an exact comparison down to the second. Therefore 4/10/2008 is LESS THAN 4/10/2008 8:27:41 PM
You state you don't know the field type. That would be the first problem to solve, find out. You can do that with:-
SELECT DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Order_Master' AND
COLUMN_NAME = 'Order_Date'
If its not one of the datetime types it should be converted, if that isn't your responsibility then get on to someone who does have the responsibility.
The fact that you are concerned about the 'format' of the date indicates that you may be building the SQL using concatenation. If so stop doing that. Use a command with a parameter and pass in the date as date type.
Now your issue is one of how the date is entered at the client end and getting it into an unambigous format that can be parsed as a date in the ASP code.
If that is not something you have solved add a comment to this answer and I'll expand this answer.