How to write this query in PL/SQL? - plsql

How do I write this?
DECLARE
STARTDATE DATE;
ENDDATE DATE;
BEGIN
STARTDATE='&&STRTDTE';
ENDDATE='&&ENDATE';
...
...
WHERE AAA_BBB.TR_DATE BETWEEN 'STARTDATE' AND 'ENDDATE';

I'm guessing that you intend the script to prompt the user for the STRTDTE and ENDATE values (why "DTE" in one and "DATE" in the other, btw?).
Assuming that the user enters both dates in the current default format, then all you need is to change your where statement:
WHERE AAA_BBB.TR_DATE BETWEEN STARTDATE AND ENDDATE;
It might be safer, however, not to assume what the current format is, and actually prompt for the date in a specific format, then store the responses as dates using that specific format:
STARTDATE := TO_DATE( '&&STRTDTE', 'YYYY/MM/DD' );
ENDDATE := TO_DATE( '&&ENDATE', 'YYYY/MM/DD' );
or whatever format you wish.
Also note the := rather than =

Related

SQL query for finding all the records that exist on a particular date within some date range

I have a date= 2016-12-25 at hand, and i want to find all the records of this particular date. The records in the database are stored as a range of startDate and endDate. Example
|_____Name___|___Class_____|___StartDate_____|___EndDate______|
|_____Maths___|____Lecture___|___2016-12-10____|___2016-12-30____|
so now using the sql query i want to display this class with the user selected date 2016-12-25 where I am unaware os StartDate and EndDate (All i have in hand in the user specified date, the StartDate and EndDate could differ for each subjects). Can anybody please help me out?
will it be something like this?
query: select all records where 2016-12-25 between all StartDate and endDate
This works
CREATE TABLE "classes" (
`Name` TEXT,
`Class` TEXT,
`StartDate` TEXT,
`EndDate` TEXT
);
Insert into Classes(`Name`,`Class`,`StartDate`,`EndDate`)
values ("Maths","Lecture","2016-12-10","2016-12-30");
select *
from Classes
where "2016-12-20" between StartDate and EndDate;
Do not forget to check the input strings are representing valid dates in the choosen format ('YYYY-mm-DD')
Try below query
SELECT *
FROM `TaleName`
WHERE
StartDate >='2016-12-25'
AND EndDate <='2016-12-25 '

SQL Server Filtering by DateTime column, when TIME portion is provided sometimes

In an SSRS report, the user searches based on start date and end date.
The challenge is, as I discovered recently, he sometimes, not always, provides the time component while searching.
Currently, the filter is done like this:
if #pEndDate is null
SET #pEndDate = getdate()
SET #PEndDate = DateAdd(dd,1,#PEndDate)
SELECT ........
FROM .....
WHERE ( Createdon >= #PStartDate AND Createdon < #PEndDate)
This is fine when he searches without time (example - #PStartDate = 2/23/2015 and #PEndDate = 2/24/2015)
How should I structure the query to deal with the time portion when he provides it? (example - #PStartDate = 2/23/2015 15:00 and #PEndDate = 2/24/2015 15:00)
If this is answered elsewhere, please point me to it. Thank you.
If you just want to match the date part then there are lot options.
1) You can use the Date type for the parameter PEndDate and PStartDate to nullify the time part
2) You can use the Convert method to get only date part of the parameter while matching.CONVERT (DATE, #PEndDate) OR CONVERT(varchar,#PEndDate,103)
3) Get Date Part only from DateTime using DateTime functions
ATEADD(dd, 0,
DATEDIFF(dd, 0, #PEndDate))
4) Get Date Part only from DateTime using FLOOR and CAST functions
CAST( -- Convert the integer to DATE
FLOOR(-- Get largest Integer less than or equal to the decimal value
CAST(GETDATE() AS DECIMAL(12, 5)) -- Convert DATETIME to DECIMAL)
AS DATETIME) 'Date Part Only'
5) Get Date Part only from DateTime using DATEPART and CONVERT functions
CONVERT(VARCHAR(4),DATEPART(YEAR, #GETDATE))
+ '/'+ CONVERT(VARCHAR(2),DATEPART(MONTH, #GETDATE))
+ '/' + CONVERT(VARCHAR(2),DATEPART(DAY, #GETDATE))
'Date Part Only'
Use whichever method suits you and you find fancy.
UPDATE
As you mentioned you need to get the time part to 00:00 with date so you can try as,
SELECT CAST( convert(varchar(10),GETDATE(),112) AS DATETIME)
--This will give you 2015-02-27 00:00:00.000
SELECT DATEADD(ms,-3, DATEADD(day, DATEDIFF(day,0,GETDATE())+1,0))
--This will give you end of days time 2015-02-27 23:59:59.997
SELECT CONVERT(nvarchar,getdate(),103) + ' 12:59:59 PM'
--This will give you custom time 27/02/2015 12:59:59 PM

Returning a date with time, when passed utc_date and timezone as input

I have an Oracle table which has a date column ( say its name is start_date) that has stored date as UTC date. I have another column that stores a timezone (like 'America/Los_Angeles'). My requirement is I need to display the date column with timestamp corresponding to the timezone stored in the timezone column.
I initially wrote a function that accepts utc_date and the timezone and returns the date as below:
return utc_date + (SUBSTR (TZ_OFFSET (timezone), 1, 1) || '1')
* TO_DSINTERVAL (
'0 '
|| SUBSTR (TZ_OFFSET (timezone), 2, 5)
|| ':00');
but I realized a flaw. It calculates offset based on current time. So it now returns -00 08:00:00.000000 for Los_Angeles. But if the date stored in the utc_date was a date when daylight was enforced, the tz_offset value is not valid anymore. Can someone provide me some pointers how can I approach this problem?
I found a solution to my problem. Instead of relying on TZ_OFFSET, I decided to do the following
return cast(from_tz(cast(utc_date as timestamp),'UTC') at time zone timezone as date);
This is returning me the desired date. If anyone see a flaw let me know

Insert date into a SQLite database

As a part of a parametrized query I am trying to insert date from the plannerCalendar.
Params.ParamByName('D').AsDate := JulianDateToDateTime(PlannerCalendar1.Date);
This will not work.
Any ides ?
EDIT :
Even a simpla date insert will not work:
with ClientdataSet1 do
begin
Close;
CommandText :='';
CommandText :='INSERT INTO TLOG (DATE) VALUES (:D)';
Params.ParamByName('D').Value := Plannercalendar1.Date;
Execute;
I get :
When I do this (just to test) :
CommandText :='INSERT INTO TLOG (DATE) VALUES (date(julianday("now", "LOCALTIME")))';
The date gets inserted.
When I use this (looks promising) :
Params.ParamByName('D').Value := DateTimeToJulianDate(Plannercalendar1.Date);
The date inserted in the database is OK but the cxgrid displays the date funny (bellow):
Changing of the parameter does not help either.
VALUES (julianday(:D),
If I change the DATE field to CHAR in the database then the :
DateToStr(Plannercalendar1.Date);
works properly....
I store datetime in SQL timestamps:
SomeQuery.ParamByName('PARAM').AsSQLTimeStamp := DateTimeToSQLTimeStamp(Now);
SomeDateTime := SQLTimeStampToDateTime(SomeQuery.ParamByName('PARAM').AsSQLTimeStamp);
Take a look at this functions From Data.SqlTimSt unit:
DateTimeToSQLTimeStamp
SQLTimeStampToDateTime

I want to combine date and time and compare with utc date

When I write this query
SELECT Convert(datetime,Convert(varchar,CAST(GETUTCDATE() AS DATE))+' '+
CONVERT(varchar, cast(meas_pain.datetime AS time))) FROM meas_pain
it works for me but when I use the same part in WHERE clause it gives error 'Conversion failed when converting date and/or time from character string.'
SELECT schedules.id
FROM meas_pain LEFT JOIN schedules ON schedules.id=meas_pain.schd_id
WHERE meas_pain.schd_id=9150 AND
Convert(datetime,(Convert(varchar,CAST(GETUTCDATE() AS DATE))+' '+
CONVERT(varchar, cast(meas_pain.datetime AS time)))) <
CONVERT(datetime,DATEADD(Minute,0,getutcdate()))
can anybody explain??
I am not sure why this error does not appear in your select statement, since I can reproduce the error using just
SET DATEFORMAT DMY;
SELECT CONVERT(DATETIME, CONVERT(VARCHAR,CAST(GETUTCDATE() AS DATE)))
Example of Error
You are relying on localised conversion settings, you should use explicit conversion, e.g.
SET DATEFORMAT DMY;
SELECT CONVERT(DATETIME, CONVERT(VARCHAR, CAST(GETUTCDATE() AS DATE), 111), 111)
By explicitly defining the date format to convert both to varchar and from varchar (111) you can avoid any implied conversions.
However, If your dates/times are stored as such there should be no need for all the conversion to and from varchar, this is just more chance for things to go wrong, and unnecessary work, you can simply add a time to a datetime. e.g.
DECLARE #Date1 DATETIME = DATEADD(HOUR, 1, GETUTCDATE()),
#Date2 DATETIME = DATEADD(DAY, 1, GETUTCDATE());
SELECT [Date1] = #Date1,
[Date2] = #Date2,
[Date1/Time2] = CAST(CAST(#Date1 AS DATE) AS DATETIME) +
CAST(#Date2 AS TIME);
From what I can gather from your query you are just trying to get results where the time of meas_pain.datetime is less that the current UTC time, regardless of date. So you should be able to simplify your query to just:
SELECT schedules.id
FROM meas_pain
LEFT JOIN schedules
ON schedules.id = meas_pain.schd_id
WHERE meas_pain.schd_id = 9150
AND CAST(meas_pain.[DateTime] AS TIME) < CAST(GETUTCDATE() AS TIME);
And remove further redundant conversions.
Simplified example on SQL Fiddle
ADENDUM
Apparently this time comparison is not what you are after (although it is what the query you have posted is doing), so I am assuming GETUTCDATE() is just for demonstration.
The conversion you are trying to perform is equivalent to this:
CAST(CAST(GETUTCDATE() AS DATE) AS DATETIME) + CAST(meas_pain.[DateTime] AS TIME)
Another example on SQL Fiddle using the above conversion

Resources