how to get excel to treat a date as a date not a string when doing CopyFromRecordset - sql

I have an SQL query from SQL Server which returns dates as a string in the format "YYYY-MM-DD".
If I enter a date in this format into a cell, it's recognised as a date.
But when I populate a worksheet with CopyFromRecordset, it seems to be treated as a string.
Any formula which uses the cell converts it to a date first. For example, if my dates are in col A and I make a new column B filled with a formula =A1 + 0
the formula returns my date, as a date.
The problem:
I use the Recordset data for a few things, one of them being a pivot table.
The pivot table does not see my dates as dates. I can't group as dates, for example. My hack is to make a new column which is basically =A1 + 0
I'm going to change my macro to automate this adding a zero, but I wonder if there's a way to get it right from the moment the CopyFromRecordset is performed.

The easiest way would be to do the conversion on the SQL server e.g.
SELECT CAST(date_text AS DATE) FROM TestExcelDates;

CopyFromRecordset is well known for causing data type / cell formatting issues in Excel.
I think I remember reading somewhere this is because the datatype of the recordset is ignored and Excel attempts to work out the format of each column itself based on a subset of the data in the recordset.
The best way round this is to set the cell formatting in the destination range before performing the CopyFromRecordset.

I had this problem after I had changed a view on my SQL Server database. I had changed the data type to DATE; formerly it was on an older version which didn't support DATE so I had used DATETIME. I suspect Excel doesn't always recognize the Date datatype through the SQLOLEDB provider, but it does recognize DATETIME. The field of interest is meas_date. So I altered the view by changing this to a cast SELECT CAST(meas_date AS DATETIME) AS meas_date, ... and refreshed the query in Excel. Worked!

Use the CDate() function when populating cells with dates from the recordset. This will convert the string to a date value.
Edit
That works for setting individual cell values. For using CopyFromRecordset I think you need to do the conversino in the SQL query, so the column returned by the query is a date type rather than a string.

I had this problem too importing data from Teradata, and got around it by first formatting the date columns with NumberFormat = "m/d/yy h:mm;#" (24 hr date) then stepping through the date fields afterwards with VBA and doing ws.cells(iRow, iCol).value = ws.cells(iRow, iCol).value, it forces Excel to reevaluate the string into a date/time field.

This probably will not be the answer but will surely helps you finding the right solution for your problem
String stringCellValue = myCell.toString();
here myCell has datatype as CELL which I've converted to String format.
If u want it in desired Date format, then u can try this-
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
myCellDate = sdf.parse(stringCellValue );
Hope it helps in solving your problem...

Related

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.

convert TEXT dd/mm/yyyy in SQL column to DATE YYYY-MM-DD

I would love to know the best way to handle data that has been inputted incorrectly as dd/mm/yyyy into a sql database as TEXT and to have it converted into a new column of the table with the datatype as DATE so it is actually stored as yyyy-mm-dd.
Existing text date column name is called "olddate" with an empty column created called "truedate" to house the new data. Each row has the date field, but none are able to be sorted correctly because of this issue.
Any ideas how I can slice and dice the current date into a new DATE field friendly version?
Thanks in advance :-)
That is style 103. So use:
select convert(date, col, 103)
Are you using Oracle? If so, TO_DATE is what you want. You can take in a string that represents a date and convert it to a date using the format you pass it.

Changing date formats in Excel using

I have a excel sheet in which a column has date date in the format "yyyyMMdd" and I want to format it as "yyyy/MM/dd".
For this I tried to use following line inside macro, but it's converting cell data as "###.....#" instead of changing date format.
Sheet1.Range("C3", "C302").NumberFormat = "yyyy/mm/dd"
...
result = "#####...#"
...
Can someone tell me why it's happening? Is there any other way for doing this?
If a date/time cell appears full of # signs, it means that the column is too narrow to display the format.
Make the column wider to accommodate the full width of the selected date format.
See this screenshot. Both columns have the same format. Column A is too narrow to show the dates. Column B is wide enough.
Edit after discussing in chat:
The screen shot you posted in chat is this:
The "dates" you are referring to are not dates. They are numbers that are way higher than what Excel uses for dates in this millenium.
Excel stores dates as whole numbers, starting as 1 for 1/1/1900. What you show in your screenshot are numbers way higher than Excel dates.
Your number 20150930 is NOT what Excel considers Sep-30-2015. For Excel, that date would be the number 42277, which you can perfectly format as that date.
The reason that your "dates" formatted with your format string come out as ##### is that the numbers are way higher than what Excel can interpret as dates.
You will need to convert your numbers to real Excel dates, which you can do with a simple formula. With your first "date" number in cell A1, you can use the formula
=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))
to return a value that Excel regards as a true date for Sep-30-2015 in this screenshot:
So, the reason for all the # signs is that the numbers you are trying to format as dates are too big for dates in Excel's algorithms.
With all the good answers, I will add simple vba solution...
Option Explicit
Sub FormatDate()
Dim xlRng As Range
Dim xlShtRng As Range
'//- Date format 20160112
Set xlShtRng = [A3:A10] '//- or [A3, A6, A10]
For Each xlRng In xlShtRng
xlRng.Value = DateSerial(Left(xlRng.Value, 4), Mid(xlRng.Value, 5, 2), Right(xlRng.Value, 2))
xlRng.NumberFormat = "yyyy/mm/dd" '//- 2016/01/12
Next
End Sub
Please try this..
=LEFT(A1,4)&"/"&MID(A1,5,2)&"/"&RIGHT(A1,2)

Date range comparison using varchar columns in Teradata

I've been tasked to take a calendar date range value from a form front-end and use it to, among other things, feed a query in a Teradata table that does not have a datetime column. Instead the date is aggregated from two varchar columns: one for year (CY = current year, LY = last year, LY-1, etc), and one for the date with format MonDD (like Jan13, Dec08, etc).
I'm using Coldfusion for the form and result page, so I have the ability to dynamically create the query, but I can't think of a good way to do it for all possible cases. Any ideas? Even year differences aside, I can't think of anything outside of a direct comparison on each day in the range with a potential ton of separate OR statements in the query. I'm light on SQL knowledge - maybe there's a better way to script it in the SQL itself using some sort of conversion on the two varchar columns to form an actual date range where date comparisons could then be made?
Here is some SQL that will take the VARCHAR date value and perform some basic manipulations on it to get you started:
SELECT CAST(CAST('Jan18'||TRIM(EXTRACT(YEAR FROM CURRENT_DATE)) AS CHAR(9)) AS DATE FORMAT 'MMMDDYYYY') AS BaseDate_
, CASE WHEN Col1 = 'CY'
THEN BaseDate_
WHEN Col1 = 'LY'
THEN ADD_MONTHS(BaseDate_, -12)
WHEN Col1 = 'LY-1'
THEN ADD_MONTHS(BaseDate_, -24)
ELSE BaseDate_
END AS DateModified_
FROM {MyDB}.{MyTable};
The EXTRACT() function allows you to take apart a DATE, TIME, or TIMESTAMP value.
You have you use TRIM() around the EXTRACT to get rid of the whitespace that is added converting the DATEPART to a CHAR data type. Teradata is funny with dates and often requires a double CAST() to get things sorted out.
The CASE statement simply takes the encoded values you suggested will be used and uses the ADD_MONTHS() function to manipulate the date. Dates are INTEGER in Teradata so you can also add INTEGER values to them to move the date by a whole day. Unlike Oracle, you can't add fractional values to manipulate the TIME portion of a TIMESTAMP. DATE != TIMESTAMP in Teradata.
Rob gave you an sql approach. Alternatively you can use ColdFusion to generate values for the columns you have. Something like this might work.
sampleDate = CreateDate(2010,4,12); // this simulates user input
if (year(sampleDate) is year(now())
col1Value = 'CY';
else if (year(now()) - year(sampleDate) is 1)
col1Value = 'LY'
else
col1Value = 'LY-' & DateDiff("yyyy", sampleDate, now());
col2Value = DateFormat(sampleDate, 'mmmdd');
Then you send col1Value and col2Value to your query as parameters.

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.