I have a very simple tool that runs a stored procedure from a database, puts the results into a DataTable, then writes the DataTable to a file via Response. The purpose is to take the data from a table on SQL Server, then use a 3rd-party tool to upload it to an Oracle database.
The problem I encounter is that date is stored, in SQL Server, as such: 2011-05-01 00:00:00.000.
However, when I access it via my SqlDataReader and put it into my DataTable, it ends up formatting as: 5/1/2011 12:00:00 AM.
So I figured I could just explicitly parse it as an OracleDateTime. I have the following column in my DataTable:
records.Columns.Add("Date", typeof(OracleDateTime));
As well as this bit where I am reading the results:
row["Date"] = OracleDateTime.Parse(rdr["Date"].ToString());
I also tried SqlDateTime for kicks, but ultimately, I end up with the same incorrectly formatted string. I just want it to stay the same way SQL returns it in the query - how can this be done?
The date is not stored that way in SQL server; what you see in your ad-hoc queries is a conversion from the internal numeric storage to that format.
When you read it in, you should be converting rdr["Date"] to a DateTime.
If you want that specific format in your code, you should format it using .NET's formatters when you output it.
Related
I would like to store a c# object in SQL server. I thought about the following options:
Read object byte memory stream and save them into the database (but
not readable in sql)
Json, readable, easy to convert but what data type? (only a datatype for sql 2016)
XML, a bit less readable, easy to convert, there is an XML dataType
What's the best practice to store a C# object in a sql column and why?
I am using SQL 2014, so I think option 3 is the best?
Edit:
Note: it's not data to query, I just want to load a object which I have cached into a c# object in memory. And perform some logic on that in c#. It just takes a while to get the data from another database, therefore I save all my data in a custom object. Therefore I don't think I should use ORM
If it's just to throw in a database to read back at some point later by a key, then go with (2) and just use an nvarchar(max) field type.
If it's data to query, then you should probably design a schema to match and use an ORM.
If you are more positive towards option B, then you can store json-serialized string of any object[or datatype] in sql server as NVARCHAR(MAX) field.
And when you want to read it you can easily de-serialize that string in original format.
e.g.
Demo d1=new Demo();
//store this json into database.
string json= JsonConvert.SerializeObject(d);
// Now while reading fron db
Demo d2= JsonConvert.DeserializeObject<Demo>(json);
I'd go for JSON serialisation, it's just text, so when storing things like "user profile settings" or other types of structural data you're covered as you can read and write JSON in any language. Now SQL server has also understood this, like the XML support that was such a hype 8-10 years ago one can now store JSON with a good deal of TSQL support for those that need to update the data, like when you need to fix all updates for all user where...
anyway, have a look at the article. JSON in SQL Server 2016-2017
When going to and from JSON you should test your properties as some data types might not convert back and forward nice depending on things like regional specific settings like date and decimal values.
I know the question is a bit confusing. Please let me elaborate.
Suppose
I have a table student master which has a column DOB
I have inserted a record and in DOB I have inserted '1991-01-01'
running select statement from sql server is returning date in the same format as it is inserted '1991-01-01' but when I am running the same query from C# using SqlDataAdapter then its returning date as '01-01-1991'
Can anyone explain why it is happening and is there any way to fetch the date in same format as it is inserted.
Query
Is it possible to get the DateTime using SqlDataAdapter as it was inserted?
P.S: column data type is Datetime
let's separate the wheat from the chaff :)
if for your needs meaningful is data type (datetime in this case), then formatting does not matter at all. All layers which will exchange or process the data will use data type information for that.
But
if the meaningful part is formatting, i.e. string representation of the data, then you need to consider the appropriate settings of UI tools you use to display your data. SSMS, for example, uses regional settings for that. If you need to visualize data in the identical manner, so you need the identical strings, you should take care of formatting by your self or in another words, you need to convert your datetime data to string in the same way in all places where you need it.
In T-SQL, for example, you could use CAST and CONVERT functions for formatting your data in a format you need.
If you can't match up the "Cultures" between the SQL Server and the machine you're building the application on (and, in fact, you cannot rely on that really if you're application is going to be deployed to other machines!), then the cheap and quick way round it is to run your date returns through a parse function such as this:
private string FncFormatDate(string date)
{
DateTime formattedDate;
if (DateTime.TryParse(date, out formattedDate))
{
return formattedDate.ToString("yyyy-MM-dd");
}
else
{
return "Invalid date";
}
}
I hope this answers your question.
I'm reading a timestamp from a mysql table using an OdbcDataReader. When I look at the data in the table it is in the format 2013-09-12 11:11:09. But the reader seems to read it in the format 12/09/2013 11:11:09.
I then try to insert this into another mysql table but receive the error:
Incorrect datetime value: '12/09/2013 11:11:09' for column 'timestamp'
at row 1
How can I sort out this difference in formatting? Should I be referencing some Unix timestamp value somehow?
The data shouldn't be in the table in any text format. It's just a date and time.
You'll see the format when you convert the data to a string - which you should do as rarely as possible. In particular, when you're inserting the data into a different table, you shouldn't use a formatted value at all - you should use a DateTime in parameterized SQL.
Basically, unless you really need a string representation of the data, you should keep it in the "native" representation (DateTime in this case). Every time you have a conversion to or from text, that's an opportunity for failure. Dates and times are hard enough with time zones etc, without extraneous conversions getting involved.
How are you looking at the data "in the table"? I'm not familiar with the MySQL implementation, but with Oracle and Sql Server datetime values are stored in an unreadable binary format, and translated to a readable timestamp by the query tool. MySQL is likely doing something similar.
try to insert this into another mysql table
If you care about format when you're inserting the data, you're doing something really bad. That's a strong indication you're using a technique that will be vulnerable to sql injection attacks, rather than parameterized queries. If you use parameterized queries, you assign a C# datetime type to the query parameter value directly, and the ADO.Net object handles any formatting you need. At that point, anything you can successfully DateTime.Parse() or DateTime.TryParse() becomes a valid input for your query.
I am trying to do a C# dataset caparison between two datasets from two different DB's. Dataset one is from Oracle and Dataset two is from SQL Server and I'm comparing these datasets after an ETL jobs runs to move data from Oracle to SQL Server to validate the results. Problem I'm having is that the data in SQL Server matches but the Dates are in a different format from source to destination and also decimal point rounding.
Has anyone got a good way to circumvent this problem. I was thinking about changing my queries from the source and destination tables that fill the Dataset to format the dates etc... so the comparison would be easier but I wanted to see was there any other way?
For the date formats set the NLS_DATE_FORMAT environment variable to the desired format. This assumes that you catch the data in a string. Oracle will format the date to the format you specified. For the decimal point rounding I don't get it. Those numbers should be the same. In case you get a decimal point and want a comma, use NLS_MUMERIC_CHARACTERS 'DG' to choose which character to use a Decimal point or Group separator.
For example '.,' selects a '.' for decimal point and a comma for group separator.
The environment variables can be set from the clients OS and also from within the Oracle session. To do this, issue alter session set nls_date_format = 'YYYYMMDDHH24MISS'; or whatever format suits you best.
I send the registration date parameter to mysql database like "22-12-2010". But my sql date date type is in another format how can I change the date format like "2010-12-22" also I have to insert this into table.
Give code in C#,asp.net code behind either sql query statement!
Use this comprehensive MSDN pages as your guide: Standard Date and Time Format Strings and Custom Date and Time Format Strings.
There are many examples on those pages on how to reformat a date string in C#, and they also provide a good clear explanation on how date formatting works in the DateTime class.
Once you've reformatted your date string in C#, you should be able to pass it on down without needing to use SQL to reformat it.