Delphi & Absolute database : Delete Query - delphi

Why is it that my query does not work ?
Form1.ABSQuery1.Close;
Form1.ABSQuery1.SQL.Clear;
Form1.ABSQuery1.SQL.Text:='DELETE FROM LOG WHERE status = ''YES'' and DATE BETWEEN :d1 and :d2';
Form1.ABSQuery1.Params.ParamByName('d1').Value :=cxDateEdit1.Date;
Form1.ABSQuery1.Params.ParamByName('d2').Value :=cxDateEdit2.Date;
Form1.ABSQuery1.ExecSQL;
Form1.ABSTable1.Refresh;
I get this error :

You should be using AsDateTime in your Params setting code.
Form1.ABSQuery1.SQL.Text:='DELETE FROM LOG WHERE status = ''YES'' and DATE BETWEEN :d1 and :d2';
Form1.ABSQuery1.Params.ParamByName('d1').AsDateTime :=cxDateEdit1.Date;
Form1.ABSQuery1.Params.ParamByName('d2').AsDateTime :=cxDateEdit2.Date;
Form1.ABSQuery1.ExecSQL;
Using Value converts the cxDateEdit1.Date to a generic string format for assignment, and that doesn't properly convert it to the YYYY-MM-DD format that most databases (including ABS) expect. Properly using AsDateTime allows the database driver/component to convert to the specific date format the DBMS uses.
Also, is your database field really named DATE? Date is usually a reserved word or function name in most DBMS, and if it is it usually needs to be quoted.

Form1.ABSQuery1.Params.ParamByName('d1').DataType := ftDateTime;
Form1.ABSQuery1.Params.ParamByName('d1').Value :=cxDateEdit1.Date;
You must explicitly specify the data type of the parameter to it had no such problem, and then convert to a string does not need to

Related

thingsboard rulechain - filter script node to check if metadata timestamp is greater than server timestamp

I have created an asset variable with a timestamp attribute (dateTo) and would like to compare this to the current server time.
Ho do I get the server/system time of the Thingsboard. TBEL documentation states that "we have added Date class that you are able to use without the package name" so I should be able to get the server time with:
Date
Testing in the Test Filter Function doesn't error while using:
return Date > metadata.dateTo;
But does not assess correctly (changing the value around generates a False result either way).
Each metadata field has a string type, instead of integer as expected. So before comparison you have to convert metadata.dateTo to integer:
return Date.now() > +metadata.dateTo;

Snowflake Tasks causing error in timezone in queries

I am running a simple insert query inside a stored procedure with to_timeatamp_ntz("column value") along with other columns.
This works fine when I am running it with the snowflake UI and logged in with my account.
This works fine when I am calling it using python scripts from my visual studio instance.
The same stored procedure fails when it is being called by a scheduled task.
I am thinking if it has something to do with the user's timezone of 'System' vs my time zone.
Execution error in store procedure LOAD_Data(): Failed to cast variant
value "2019-11-27T13:42:03.221Z" to TIMESTAMP_NTZ At
Statement.execute, line 24 position 57
I tried to provide timezone as session parameters in task and in the stored proc but does not seem to be addressing the issue. Any ideas?
I'm guessing (since you didn't include the SQL statement that causes the error) that you are trying to bind a Date object when creating a Statement object. That won't work.
The only parameters you can bind are numbers, strings, null, and the special SfDate object that you can only get from a result set (to my knowledge). Most other parameters must be converted to string using mydate.toJSON(), JSON.stringify(myobj), etc., before binding, eg:
var stmt = snowflake.createStatement(
{ sqlText: `SELECT :1::TIMESTAMP_LTZ NOW`, binds: [(new Date).toJSON()] }
);
Date object errors can be misleading, because Date objects causing an error can be converted and displayed as strings in the error message.
I found the issue:
my Task was using a copy paste effect similar to this:
CREATE TASK TASK_LOAD_an_sp
WAREHOUSE = COMPUTE_WH
TIMEZONE = 'US/Eastern'
SCHEDULE = 'USING CRON 0/30 * * * * America/New_York'
TIMESTAMP_INPUT_FORMAT = 'YYYY-MM-DD HH24'
AS
Call LOAD_an_sp();
The Timestamp input format was causing this.

Getting an error while inserting data using stored procedure in mvc entity framework

I'm getting an error
converting data type nvarchar to datetime.
Where I did mistake?
var exec = db.Database.ExecuteSqlCommand("sp_InsertTicketChat #TicketId,
#FullName, #Description,
#LastCorrespondanceBy,#LastCorrespondanceOn",
new SqlParameter("#TicketId", TicketId),
new SqlParameter("#FullName", FullName),
new SqlParameter("#Description", Description),
new SqlParameter("#LastCorrespondanceBy", FullName),
new SqlParameter("#LastCorrespondanceOn",
DateTime.Now.ToString())
);
This is my stored procedure through which I want to insert data. What can I do ?
INSERT INTO tblTicketChat
(
TicketId,
FullName,
[Description],
LastCorrespondanceOn,
LastCorrespondanceBy
)
VALUES
(
#TicketId,
#FullName,
#Description,
GETDATE(),
#LastCorrespondanceBy)
Now I got the root cause of the issue you were facing.
Ideally, DateTime.Now.ToString() should have got converted to SQL Server Datetime data type when being assigned to the #LastCorrespondanceOn parameter of your stored procedure but it threw an exception.
The reason is date time format settings of your operating system.
The thing is when you perform DateTime.Now.ToString() in your C# language based client code it takes the default settings of date time format from your operating system. Look at the date time format currently set on my windows 10 box:
Due to this setting the code DateTime.Now.ToString() emits 27-07-2017 18:07:37. The output you're seeing is dd-MM-yyyy format.
Now this dd-MM-yyyy date format is not recognizable by SQL Server as per your default language settings.
SQL Server can recognize two date time formats when sent as string from client side
International date format yyyy-MM-dd also known as ISO 8601 .
Date format controlled by user login's dateformat setting. You can run dbcc useroptions command to see the value of setting. For me it is set to mdy
Due to this mismatch in the date time format being sent by your C# code (because of your operating system) and what SQL server can parse, you faced the issue.
When you did the conversion explicitly by date.ToString("yyyy-MM-dd"); you simply aligned it ISO 8601 international date time format supported by SQL Server so it started to work.
The default date time format (ISO 8601) of SQL Server is a configuration of the collation you are using currently which you can check in your SQL Server instance properties as shown below:
It is strongly recommended that you should always use SQL's date time format when passing it in string format as mentioned in this thread.
So you can solve your problem in three ways:
Change the default date format of your OS to align it to SQL Server (Not recommended). It will never be feasible on all client computers where your application runs.
Use custom date format while calling ToString method as you have done to align it to one of the formats supported by SQL Server. Best format is ISO 8601 format which you've used.
Don't convert it to string. Just pass the date time value as is.
var exec = db.Database.ExecuteSqlCommand("sp_InsertTicketChat #TicketId,
#FullName, #Description,
#LastCorrespondanceBy,#LastCorrespondanceOn",
new SqlParameter("#TicketId", TicketId),
new SqlParameter("#FullName", FullName),
new SqlParameter("#Description", Description),
new SqlParameter("#LastCorrespondanceBy", FullName),
new SqlParameter("#LastCorrespondanceOn",
DateTime.Now) //Don't call .ToString here
);
Approach # 3 is the best deal. More details here as to why you shouldn't use strings but the date time data type while dealing with SQL Server datetime columns.
I solve this issues by using MSSQL string formatted (dd-MM-yyyy) in my storedprocedure
I solved this issue by doing some changes.
DateTime date = DateTime.Now;
string strDateTime = date.ToString("yyyy-MM-dd");
var exec = db.Database.ExecuteSqlCommand("sp_InsertTicketChat #TicketId, #FullName, #Description, #LastCorrespondanceOn, #LastCorrespondanceBy",
new SqlParameter("#TicketId", TicketId),
new SqlParameter("#FullName", FullName),
new SqlParameter("#Description", Description),
new SqlParameter("#LastCorrespondanceBy", "raza"),
new SqlParameter("#LastCorrespondanceOn", strDateTime)
);

Deserialize joda time from string in grails?

I had a LocalTime field (using Joda Time) in Grails domain class.
Class WorkDone{
LocalTime duration
}
Now I have altered this field to String (with Text constraint) so that it can support duration larger than 24 hrs.
String duration
The problem is there is already some data in database. And I want to sanitize that data through database migrations in Grails. I am using Postgres which saves LocalTime as Bytea (binary data).
When I call WorkDone.duration it returns me a String of the form:
\xaced0005737200176f72672e6a6f64612e74696d652e4c6f63616c54696d65fffff44abbf29def0200024a000c694c6f63616c4d696c6c69734c000b694368726f6e6f6c6f677974001a4c6f72672f6a6f64612f74696d652f4368726f6e6f6c6f67793b78700000000000000000737200276f72672e6a6f64612e74696d652e6368726f6e6f2e49534f4368726f6e6f6c6f67792453747562a9c811667137502703000078707372001f6f72672e6a6f64612e74696d652e4461746554696d655a6f6e652453747562a62f019a7c321ae30300007870770500035554437878
How can I extract time from this string?
Your data is scaped in bytea Hex format, (starts with \x) take a look at PostgreSQL docs
http://www.postgresql.org/docs/current/static/datatype-binary.html
You have to unescape it before read as ObjectInputStream ang get the LocalTime object, unescape it and then try again as Raphael suggest.
You should have done a data-migration before changing your Data-type to String.
Here is what you should do.
1. Change the Data-type of the field back to LocalTime.
2. Create a new field with String Date.
3. Write a script that would get all date in LocalTime and convert it to String and save it in new field.
4. Once you have your data migrated, delete the old field and then rename your new field to duration.
I ended up doing the following -
grailsChange{
change{
sql.eachRow("Select id,duration from work_done"){
def wdId = it.id
def durationObj = (LocalTime)(new ObjectInputStream(new ByteArrayInputStream(it.duration))).readObject()
durationObj = durationObj.toString().substring(0,8)
WorkDone.executeUpdate("update WorkDone wd set wd.duration=:newDuration" +
"where wd.id=:wdId",
[newDuration:durationObj ,wdId:wdId ])
}
}

Override Grails Error Messages to format Dates and Numbers

I have created a domain with a Double field. When the validation occurs it throws the error message with size value showing the number with commas. Following are the detials
Groovy Class
class Quote {
String content;
Double size;
static constraints = {
content(maxSize:1000, blank:false)
size(min: 0.00D, max:999.99D)
}
}
Value entered "11111", error obtained "Size 11,111 is exceeded the limit". I have added the property key/value pair in messages.properties.
Here, I would like to get the message back without the commas. My main aim is to take the key and format the message returned based on my requirements. I require this as I have other fields that need conversion. For example, a date is validated but when showing the error the Gregorian date needs to be converted to an Islamic date and shown to user.
Does anyone know if I can do something to make this work.
I have tried the solution provided in http://ishanf.tumblr.com/post/434379583/custom-property-editor-for-grails but this did not work.
I have also tried modifying the messages values, but this is not flexible in case of my date issue. Example, for a key value pair, instead of using {2} as a place holder I could use {2, date, mm/dd/yyyy}, but for Islamic dates I want to format and show things differently.
Also, please note I have created a separate key for default date formatting for my application.
Would appreciate the help.
In grails, the return of a constrain is an already translated string.
You can create a taglib to format that, or enhance the
Another option would be custom validators. A custom validator can return false or a key when failing.
For example in your domain class, to vaildate a field:
myDateField validator: {val, obj -> obj.myShinyDateValidatorMethod(val) }
private myShinyDateValidatorMethod() {
if (isNotValidDate(val) {
return [the_message_key, val.formatedAsYouWand]
}
}
and, in your properties file you have to have defined the key:
the_message_key=This date: {3} is not valid
The trick here is that in the return from the validator, first string is the key and the rest are parameters for that key, but grails already uses {0}, {1}, {2} placeholders for className, fieldName and value, and the first parameter that you pass will be used as {3} placeholder.
Hope this helps

Resources