In my app I'm using node mssql module to input datetime into a SQL Server database. The problem is that in the database datetime is always changed and time is one hour less then the one that I input.
async function insertDate(date, logIO) {
try {
var d = new Date(date)
var name = 'zdzmar'
const pool = await sql.connect(config)
let result = await pool.request(pool)
.input('date', TYPES.DateTime, d)
.input('name', TYPES.VarChar, name)
.input('logIO', TYPES.TinyInt, logIO)
.query(`insert clock(date, name, logIO) values(#date, #name, #logIO)`)
} finally {
sql.close();
}
}
Where is the problem?
It seems like a bug with the mssql package. I run into the same problem even when I formated the datetime into a string, the date still got converted into a different datetime, in my case 12:04pm got converted to 20:04pm, which is not directly related to timezone or UTC time.
A workaround to solve this problem is to use sql.VarChar instead of sql.DataTime.
Related
I am trying to get SQL Server date as a date object using the npm mssql package. Unfortunately it returns type = object (Orderdate is a datetime object in SQL Server).
How can I easily return the date column as an actual node.js Date object?
const sql = require('mssql')
const ordersSelect = `
SELECT TOP 20
OrderDate
FROM Orders
`
let pool = await sql.connect('mssql://sa:wonton$98#TS1\\SQL2014/Artoo')
const request = pool.request()
const orders = await request.query(ordersSelect)
var orders = orders.recordset
As far as I know, the Node module mssql cannot be configured to return SQL datetimes to Node date objects. Everything just comes back as strings inside the recordset object
However you could write some code to transform the data set after it has been loaded by the module. JavaScript can convert strings from the format yyyy-mm-dd hh:mm:ss.sss (returned by SQL Server) to its own Date object, so something like
for (var row in orders) {
orders[row].OrderDate = new Date(orders[row].OrderDate)
// or
orders[row]["OrderDate"] = new Date(orders[row]["OrderDate"])
}
to the end of your code sample provided would work.
How do I select certain set of data(rows) from sql database by the time when they are inserted? I don't see any related documents in regards to how to do this using mssql module in node.js... could anyone suggest me any reading material or something else? So my question is how to create timestamp column when data are inserted in database
Thank you
The doc seem straight forward on how to achieve it
const sql = require('mssql')
async () => {
try {
const pool = await
sql.connect('mssql://username:password#localhost/database')
const result = await sql.query`SELECT * FROM TABLE WHERE DATE BETWEEN '09/16/2010 05:00:00' and '09/21/2010 09:00:00'`
console.dir(result)
} catch (err) {
// ... error checks
}
}
I've been searching but haven't found my answer so forgive me if this question is a duplicate.
I've got a .Net C# application that is using entity framework (EF) to communicate with a SQL Server database. I'm converting a large amount of data and I need to make sure my dates are valid SQL Server datetime types. My POCO classes use a datetime2 type for the dates so a date '0201-04-11 13:00:00 PM' is valid until the insert is actually attempted in the SQL Server database. I was attempting to use DateTime.TryParseExact with something like this...
if (DateTime.TryParseExact(legacyRecord.date_paid.ToString(), "M/d/yyyy hh:mm:ss tt", new CultureInfo("en-us"), DateTimeStyles.None, out datePaid))
{
// Load record into lease payment table table
LoadLeasePayment loadLeasePayment = new LoadLeasePayment();
Decimal LeasePaymentId = loadLeasePayment.AddRecord(prodLeaseId, legacyRecord.amount_paid, datePaid, prodContext, loadDate);
}
I'm sure the solution is obvious but I cannot see the forest for the trees. Any help is much appreciated.
After parsing the string DateTime value, you'll need to verify it is within the range of the target SQL data type. The SqlDateTime structure includes static MinValue and MaxValue fields to facilitate this.
if (DateTime.TryParseExact(legacyRecord.date_paid.ToString(), "M/d/yyyy hh:mm:ss tt", new CultureInfo("en-us"), DateTimeStyles.None, out datePaid))
{
if((datePaid >= SqlDateTime.MinValue) && (datePaid <= SqlDateTime.MaxValue))
{
// Load record into lease payment table table
LoadLeasePayment loadLeasePayment = new LoadLeasePayment();
Decimal LeasePaymentId = loadLeasePayment.AddRecord(prodLeaseId, legacyRecord.amount_paid, datePaid, prodContext, loadDate);
}
}
I am retrieving data from SQL Server from a StoredProcedure using Dapper and I'm getting error
Specified cast is not valid.
and details:
Error parsing column 4 (SubTotal=0.00 - Decimal)
On SQL Server side the column SubTotal is decimal(18, 2) NULLABLE and on .NET side it's decimal?. The data being retrieved is 0.00.
I checked this answer: Dapper,decimal to double? Error parsing column X
As per answer, I replaced
il.Emit(OpCodes.Ldtoken, unboxType);
with
il.Emit(OpCodes.Ldtoken, Nullable.GetUnderlyingType(unboxType) ?? unboxType);
on line 2360 and still getting the same error.
Anyone has any ideas about this? Thanks.
Update:
I tried making column non-nullable. Also tried changing column to float (on SQL Server) and double (on .NET side). None of these worked and I was getting the same error. Then I changed column to int and now code works fine. However, I'm working with monetary values and would like to use floating point numbers. Will investigate further...
I'm executing a stored procedure as follows
var transaction = this.db.Query<PaymentTransactions>("usp_PaymentTransactionsGetSingleIfPaid", new { registrationId }, commandType: CommandType.StoredProcedure);
The relevant part of the stored procedure that returns information is below.
SELECT * FROM PaymentTransactions WHERE RegistrationId = #registrationId AND TransactionStatus = 'SUCCESS';
UPDATE 2:
Dapper is working fine. Maybe there was something wrong with my dev environment. All it took was VS restart.
Don't laugh, but I had this exact same problem with Dapper in an ASP.NET MVC project and the solution as in the comment from #erdinger worked also for me:
Close Visual Studio
Start Visual Studio again
The problem was fixed this way...
Seems like this is not Dapper specific, as I just verified the below snippet works as expected.
Try enumerating your column names explictly (instead of select *) so that the procedure returns exactly what should be mapped to PaymentTransactions. Its possible there is another non-decimal column that is misnamed?
This is using Dapper v1.13 on .Net45:
Procedure:
create procedure dbo.Test
as
select [SubTotal] = cast('0.01' as decimal(18,2))
union all
select null;
Linqpad:
void Main()
{
using (IDbConnection cnn = GetOpenConnection())
{
var users = cnn.Query<Sale>("yak.dbo.test", new { }, commandType: CommandType.StoredProcedure);
users.Dump();
}
}
public static readonly string connectionString = "Data Source=.;Initial Catalog=tempdb;Integrated Security=True";
public static IDbConnection GetOpenConnection()
{
var connection = new SqlConnection(connectionString);
connection.Open();
return connection;
}
public class Sale
{
public decimal? SubTotal;
}
Returns:
In my application I need to get database date(sysdate in case of Oracle DB) and compare it with user input date (String converted to java.util.Date). From this forum I got the following code which helps in the case of Oracle dialect.
public Date getDate() {
Session session = getHibernateTemplate().getSessionFactory().openSession();
SQLQuery query = session.createSQLQuery("select sysdate as mydate from dual");
query.addScalar("mydate", Hibernate.TIMESTAMP);
return (Date) query.uniqueResult();
}
And from this link got the following method which uses mapping file with formula.
<property name="currentDate" formula="(select sysdate from dual)"/>
Again this is specific to Oracle. I think using later method is more performance friendly, because we can get it from the same session, i.e no need of opening another session just for getting date.
I am looking for a generic solution to get date, time and timestamp from any DBMS using Hibernate. Using HQL is the preferred. Hope such a solution is available.
For those who are looking for .NET /C# solution, here is what worked for me:
// this works only with Oracle
public DateTime DbTimeStamp(ISession session)
{
// Sample returned value = "12-OCT-11 01.05.54.365134000 AM -07:00"
string sql = "SELECT SYSTIMESTAMP FROM DUAL";
ISQLQuery query = session.CreateSQLQuery(sql)
.AddScalar("SYSTIMESTAMP", NHibernate.NHibernateUtil.DateTime);
return query.UniqueResult<DateTime>();
}