read table from SQL database based on a date - r

I'm trying to read a table from an SQL database using the sqlQuery function. Specifically, I want to ceate a function with a date as input and then select the data from the SQL database which match the given date. The commands are like:
example=function(dateA)
{sqlQuery(channel,paste("select * from TABLE","where date=dateA"))}
example('2017-10-26')
Note that the format of the date on the SQL table is YYYY-MM-DD and the above command works fine when the specific date is written on the sqlQuery function. i.e. when using the command:
sqlQuery(channel,paste("select * from TABLE","where date='2017-10-26'"))
nevertheless when calling the function example with date as input this does not work.
Does anybody know if there is a way to overcome this??

That is because dateA is treated as part of the string instead of replacing the value of dateA, try instead:
example=function(dateA){
sqlQuery(channel,paste0("select * from TABLE","where date=", dateA))
}
example('2017-10-26')
Here, dateA is replaced with '2017-10-26' when you call example, and paste0 pastes "select * from TABLE","where date=" and '2017-10-26' (the value of dateA) together to form "select * from TABLE","where date='2017-10-26'"

Related

SET SESSION DATEFORM = ANSIDATE doesn't seem to be working in BTEQ

This is the BTEQ call I'm using:
.EXPORT REPORT FILE = OUTPUT_FILE;
SET SESSION DATEFORM = ANSIDATE;
SELECT * FROM TABLE_NAME
;
Dates keep coming up as IntegerDates YY/MM/DD
Teradata 16.xx. Is this not supported by BTEQ/Unix?
Update:
Fred's solution (worked like a charm)
ALTER TABLE TABLE_NAME ADD COLUMN_NAME DATE FORMAT 'MM/DD/YYYY';
The SESSION DATEFORM is a default. It applies to string values being supplied for dates or to date expressions that don't have an explicit FORMAT. It will also be used to set the FORMAT for date columns if you don't specify one in your DDL. But if a table already exists, the defined column FORMAT will override

update or convert a date time value in a sqlite database

I have a SQLite database with a TEXT column that stores a DateTime value formated like this: '11/08/2019 00:00:00'. I would like to convert the entire column contents to UTC Epoch timestamp local timezone.
Is there an Update SQL string with a DateTime function that I could run using supported SQL syntax to perform this task or should I perhaps just write a quick C# console application to do it?
I have not found any example online or in SO that would do what I need to do in this situation.
An UPDATE SQL such as :-
UPDATE mytable SET mycolumn =
CASE WHEN substr(mycolumn,3,1) = '/'
THEN
strftime('%s',substr(mycolumn,7,4)||'-'||substr(mycolumn,4,2)||'-'||substr(mycolumn,1,2)||' '||substr(mycolumn,12,8))
ELSE
mycolumn
END
;
could be used.
Example
Perhaps consider the following which will convert the column (or not if it has already been converted (or not if it does not match the dd/mm/yyyy format))
Note the below just checks the 3rd character for /, a more rigorous check could be used if desired.
:-
DROP TABLE IF EXISTS mytable;
CREATE TABLE IF NOT EXISTS mytable (mycolumn TEXT);
/* Load the testing data */
INSERT INTO mytable VALUES
('11/08/2019 00:00:00'),
('01/08/2019 00:00:00'),
('31/01/2019 00:00:00'),
('31/01/2019 13:25:33.004') /* test for micro seconds (dropped by utc)*/;
/* display data before conversion */
SELECT * FROM mytable;
/* Convert the data to unix */
UPDATE mytable SET mycolumn =
CASE WHEN substr(mycolumn,3,1) = '/'
THEN
strftime('%s',substr(mycolumn,7,4)||'-'||substr(mycolumn,4,2)||'-'||substr(mycolumn,1,2)||' '||substr(mycolumn,12,8))
ELSE
mycolumn
END
;
/* Display data as is, as formatted localised and as formatted UTC */
SELECT *, datetime(mycolumn,'unixepoch','localtime') AS local, datetime(mycolumn,'unixepoch') AS utc FROM mytable;
Note the above would NOT cater for dates such as 1/1/2019, such dates would need a more complex CASE clause.
Note that UTC is worldwide coordinated time i.e one value is stored you adjust from UTC according to the time zone
Results
Note testing in timezone that is +10 hours
When first run the results are :-
Pre-conversion :-
Post-convserion
Rerun (DROP commented out)
Pre-conversion (mixed data) :-
circled data is already converted
Post-conversion :-

Error while using SQL query with DATEADD condition in R

I am trying to extract data based on a date condition connecting to SQL from R.
My database connection is from Impala.
Below is my sample code.
dbGetQuery(src,"SELECT * FROM sample WHERE eventdate BETWEEN '2017-01-31' AND DATEADD(m,1,'2017-01-31')")
I get below error while trying to query.
Error in .verify.JDBC.result(r, "Unable to retrieve JDBC result set for ", :
Unable to retrieve JDBC result set for select * from sample where
eventdate between '2017-01-31' and dateadd(m,1,'2017-01-31') ([Cloudera]
[ImpalaJDBCDriver](500051) ERROR processing query/statement. Error Code: 0,
SQL state: TStatus(statusCode:ERROR_STATUS, sqlState:HY000,
errorMessage:AnalysisException: Could not resolve column/field reference: 'm'
), Query: select * from sample where eventdate between '2017-01-31' and dateadd(m,1,'2017-01-31').)
Instead of using DATEADD if I hard code between two dates I get the result e.g.
dbGetQuery(src,"SELECT * FROM sample WHERE eventdate BETWEEN '2017-01-31' AND '2017-02-28' LIMIT 5")
I get the result for above code but I want to use DATEADD in my code because I have multiple date conditions which I am doing using a loop function.
Any help regarding this please.
The problem is the format of your literal date string ('2017-01-31'). SQL Server, when passed a literal string for date for DATEADD will implicitly convert the value to a datetime. datetime will read the string in the format yyyy-dd-MM, translating the value to 20173101; you can see the problem there (there aren't 31 months in the year).
If you're using a literal string to pass a date(time) then use either the format yyyyMMdd or yyyy-MM-ddThh:mm:ss.sssssss as both are unambiguous regardless language and datatype.
So, for your value that would be:
WHERE eventdate BETWEEN '20170131' AND DATEADD(m,1,'20170131')
On a different note, are you really looking for rows between 20170131 and 20170228, inclusive of those dates (assuming eventdate is a date)?
remove time from your DATEADD function by using Convert function.
dbGetQuery(src,"SELECT * FROM sample WHERE eventdate BETWEEN '2017-01-31' AND convert(varchar,DATEADD(month, 1, '2017/08/25'),23)")

Date parameter mis-read in Delphi SQLite Query

What is wrong with my code:
ExecSql('DELETE FROM STLac WHERE RegN=99 AND BegDate>= 2016-12-14');
This runs, but deletes ALL the rows in STLac for RegN, not just the rows with BegDate on or after 2016-12-14.
Originally I had:
ExecSql('DELETE FROM STLac WHERE RegN=99 AND BegDate>= :myDdate,[myDate]);
which has the advantage I hoped of not being particular to the date format. So I tried the literal date should in the format SQLite likes. Either way I get all rows deleted, not just those on or after the specified date.
Scott S.
Try double quote while putting date. As any value must be provided in between quotes until and unless that column is not int
ExecSql('DELETE FROM STLac WHERE RegN=99 AND BegDate>= "2016-12-14"');
SQLite does not have datetime format as such, so you have to figure out how date is actually represented in the table and change your query to provide the same format. First execute the "select" statement in some kind of management tool,
select * from STLac where RegN = 99 and BegDate >= '2016-12-14' --(or '2016.12.04' or something else)
which displays the result in the grid; when you see the expected rows, change it to "delete" query and copy into your Delphi program.

Query a manual list of data items

I would like to run a query involving joining a table to a manually generated list but am stuck trying to generate the manual list. There is an example of what I am attempting to do below:
SELECT
*
FROM
('29/12/2014', '30/12/2014', '30/12/2014') dates
;
Ideally I would want my output to look like:
29/12/2014
30/12/2014
31/12/2014
What's your Teradata release?
In TD14 there's STRTOK_SPLIT_TO_TABLE:
SELECT *
FROM TABLE (STRTOK_SPLIT_TO_TABLE(1 -- any dummy value
,'29/12/2014,30/12/2014,30/12/2014' -- any delimited string
,',' -- delimiter
)
RETURNS (outkey INTEGER
,tokennum INTEGER
,token VARCHAR(20) CHARACTER SET UNICODE) -- modify to match the actual size
) AS d
You can easily put this in a Derived Table and then join to it.
inkey (here the dummy value 1) is a numeric or string column, usually a key. Can be used for joining back to the original row.
outkey is the same as inkey.
tokennum is the ordinal position of the token in the input string.
token is the extracted substring.
Try this:
select '29/12/2014'
union
select '30/12/2014'
union
...
It should work in Teradata as well as in MySql.

Resources