Teradata declaring dates at start of the script - teradata

This may seem like a very basic question.
I have a very large SQL statement with lots of sub queries that contain date limits in multiple where clauses
We run this query on an ad-hoc basis where i have to change the date range in the query in about 20 places. The date range is the same in all the places. So for example 1-Jan-2016 to 7-Jan-2016 as an example
In Teradata is it possible to declare the date range at the start of the query for example like a variable and then reference this variable in the code so i only need to change it once?
I have seen the answer for declaration of variable in teradata but would like to see a simple example demonstrating the concept for a date range in a stored procedure
Thank you for your time

Instead of making it a variable, it should probably be a parameter. Your stored proc would be something like this:
REPLACE PROCEDURE MyStoredProcedure
(
IN StartDate DATE
,IN EndDate DATE
)
BEGIN
DECLARE SomeOtherDate DATE; --if you need an actual date variable
--Your logic goes here
END;
Then you would set the parameters when you call the stored proc
CALL MyStoredProcedure('2015-01-01','2015-12-31');

Related

SSRS Create temporary datetime table updated with 15 minute interval - parameter not showing

I'm creating a temporary datetime table with 15 minutes increment with the following code in SSRS:
--declare #Id varchar(20), #startdate datetime,#enddate datetime
--set #ID = 'J00000041'
--set #startdate = '20210601'
--set #enddate = '20210630';
create table #tempcalendar ([dispdate] [datetime], intervaldate [datetime],intervaltime [datetime])
while #StartDate <= #EndDate+1
begin
insert into #tempcalendar values(#StartDate, convert(varchar,#StartDate,110), convert(varchar(5),#StartDate,108) )
set (#StartDate) = dateadd(minute,15,#StartDate)
end
One of the parameters doesn't appear in the Define Query Parameters dialogue box when I try to run it in SSRS and I get the message 'Must declare the scalar variable' error. I've pinpointed the issue where in the code:
set #StartDate = dateadd(minute,15,#StartDate)
I was able to perform this code in SSMS (which is where I created it initially) however I can't seem to find any information where I might have gone awry in this in SSRS. I've also tried putting parenthesis in #StartDate to show set (#StartDate) = dateadd(minute,15,#StartDate), but that didn't work.
Thank you for your help
I have seen this before when setting a variable in t-sql that is passed in from SSRS.
I think the problem is the SSRS mis-interprets the query.
I worked around the problem by setting another variable to the passed in value.
e.g.
DECLARE #StartDate2 datetime
SET #StartDate2 = #StartDate
.. then use #StartDate2 in the remainder of the query.
Also check that every instance of your variable/parameter names are exactly the same, they are case sensitive. If you pass in #X but reference #x SSRS will think this is a new parameter.
SSRS expects to be able to return metadata on the SQL in the dataset. This is how it determines the column names and data types for you. This is also why you can only have one select statement in the dataset.
You can wrap your query in a stored procedure. SSRS can call the procedure and pass in the parameters. The procedure should have one select statement that returns the results for the report to handle. The procedure can be as complex as you need it to be and abstracts that code from being embedded in the report.

How To Insert a Date using oracle form

i use oracle forms 11g. And i pass To_Date(sysdate,'dd-mm-yyyy') that is inserted to the data base and data type of the column is date. but it is inserted as 22-10-0015 instead of 22-10-2015 can you help me?
i use procedure to insert data s and oracle from button click.i need to insert dd-mm-yyyy format to the data base how to do this?
sysdate is already a date, so it doesn't make sense to call to_date() for it. You are implicitly converting it to a string, and then explicitly back to a date. The implicit step is using your Forms session's NLS_DATE_FORMAT, which is presumably DD-MM-YY from the symptoms, so you're really doing:
to_date(to_char(sysdate,'dd-mm-yy'),'dd-mm-yyyy')
The implicit string version would show the year as 15 if you ran that on its own; and the explicit conversion correctly sees that as 0015 rather than assuming 2015.
You should just pass sysdate directly; but if you're trying to strip out the time so it shows as midnight, you can use the trunc() function:
trunc(sysdate)
SYSDATE is already a DATE. You don't need to use TO_DATE to convert it into a DATE.
What it's happening is that you're converting SYSDATE into a string and you're using the YYYY mask which will translate any year over 2000 into the 00's (that's why 2015 is being converted to the year 15). If you use the RRRR mask you will get the expected result:
TO_DATE(SYSDATE,'dd-mm-rrrr')
However, this is not a good idea as it's unnecesary and could fail if the NLS_DATE_FORMAT model used for the implicit conversion to string doesn't match.

Insert multiple rows into SQL Server based on start and end dates

I need to insert several rows into a SQL Server database based on Start Date and End Date textboxes.
E.G. tbStartDate.Text = "25/12/2012" and tbEndDate.Text = "29/12/2012" therefore I need to insert individual rows for the following dates:
25/12/2012
26/12/2012
27/12/2012
28/12/2012
29/12/2012
Please can you help me with the necessary T-SQL to achieve this?
As always there are a few ways. Here are some of them:
You can write code in your app that loops through the days and inserts a single record per day. (generally the worst design)
You can call some SQL script to do it all in the database.
You can wrap up your SQL script in a stored procedure and pass in the start and end date and get the stored procedure to do it for you.
You can cross join to a pre existing tally table and use it to generate your records.
If you can provide
-the version of SQL Server that you're using
-what the table looks like
-whether you're using C# or VB
then we can help further as it can be difficult to pass dates into databases. It can be particularly difficult if you do not validate them.
Anyway here is option 3 for you.
CREATE PROC dbo.t_test
#StartDate DATETIME,
#EndDate DATETIME
AS
WHILE #StartDate <= #EndDate
BEGIN
INSERT INTO YourTable(YourDateField) VALUES (#StartDate)
SET #StartDate = DATEADD(d,1,#StartDate)
END
Then you need to call this stored procedure (called dbo.t_test) from ASP.Net and pass in your two date parametes as dates.
Declare #Startdate datetime
Select #Startdate='20121025'
While #Startdate<='20121029'
begin
if not exists(select * from dummy where DATE=#Startdate)
insert into dummy (date) values (#Startdate)
set #Startdate=#Startdate + 1
end;

How can I store the current timestamp in SQLite as ticks?

I have a SQLite database where I store the dates as ticks. I am not using the default ISO8601 format. Let's say I have a table defined as follows:
CREATE TABLE TestDate (LastModifiedTime DATETIME)
Using SQL, I wish to insert the current date and time. If I execute any of the below statements, I end up getting the date and time stored as a string and not in ticks.
INSERT INTO TestDate (LastModifiedTime) VALUES(CURRENT_TIMESTAMP)
INSERT INTO TestDate (LastModifiedTime) VALUES(DateTime('now'))
I have looked at the SQLite documenation, but I do not seem to find any option to obtain the current timestamp in ticks.
I can of course define a parameter in C# and store the value as a System.DateTime. This does result in the datetime getting stored to the database in ticks.
What I would like to do is be able to insert and update the current timestamp directly from within the SQL statement. How would I do this?
Edit:
The reason I want the data stored as ticks in the database, is that the dates are stored in the same format as stored by the ADO.Net data provider, and so that when the data is also queried using the ADO.Net provider it is correctly retrieved as a System.DataTime .Net type.
This particular oddity of SQLite caused me much anguish.
Easy way - store and retrieve as regular timestamp
create table TestDate (
LastModifiedTime datetime
);
insert into TestDate (LastModifiedTime) values (datetime('now'));
select datetime(LastModifiedTime), strftime('%s.%f', LastModifiedTime) from TestDate;
Output: 2011-05-10 21:34:46|1305063286.46.000
Painful way - store and retrieve as a UNIX timestamp
You can use strftime to retrieve the value in ticks. Additionally, to store a UNIX timestamp (roughly equivalent to ticks), you can can surround the number of seconds in single-quotes.
insert into TestDate (LastModifiedTime) values ('1305061354');
SQLite will store this internally as some other value that is not a UNIX timestamp. On retrieval, you need to explicitly tell SQLite to retrieve it as a UNIX timestamp.
select datetime(LastModifiedTime, 'unixepoch') FROM TestDate;
To store the current date and time, use strftime('%s', 'now').
insert into TestDate (LastModifiedTime) VALUES (strftime('%s', 'now'));
Full example:
create table TestDate (
LastModifiedTime datetime
);
insert into TestDate (LastModifiedTime) values (strftime('%s', 'now'));
select datetime(LastModifiedTime, 'unixepoch') from TestDate;
When executed by sqlite3, this script with print:
2011-05-10 21:02:34 (or your current time)
After further study of the SQLite documentation and other information found on date number conversions, I have come up with the following formula, which appears to produce correct results:
INSERT INTO TestDate(LastModifiedTime)
VALUES(CAST((((JulianDay('now', 'localtime') - 2440587.5)*86400.0) + 62135596800) * 10000000 AS BIGINT))
Seems like a painful way to produce something that I would expect to be available as a built-in datetime format, especially that the database supports the storing of datetime values in ticks. Hopefully, this becomes useful for others too.
Update:
The above formula is not perfect when it comes to daylight savings. See section Caveats And Bugs in SQLite docs regarding local time calculation.
The following will return the number of milliseconds since the UNIX Epoch:
SELECT (strftime('%s', 'now') - strftime('%S', 'now') + strftime('%f', 'now')) * 1000 AS ticks
It works by grabbing the number of seconds since the Unix Epoch (%s), subtracting the number of seconds in the current time (%S), adding the number of seconds with decimal places (%f), and multiplying the result by 1000 to convert from seconds to milliseconds.
The subtraction and addition are to add precision to the value without skewing the result. As stated in the SQLite Documentation, all uses of 'now' within the same step will return the same value.

How to format date and time values for SQLite?

Can't believe I have to ask this here. Even googling didn't help.
I want to do this:
insert into atable (adatefield,atimefield,adatetimefield) values (A,B,C);
adatefield is defined as DATE
atimefield is defined as TIME
adatetimefield is defined as DATETIME
What do I put for A, B and C?
It's nice that it's free but the documentation for SQLite is awful.
A date, time and datetime field will actually all store datetime, it just depends on what you insert into it, and they will all work with date strings.
You can
insert into atable values("2010-11-16","14:12:22","2010-11-16 14:12:22");
or you can actually just insert "2010-11-16 14:12:22" into all the fields and then select them back with:
select date(adatefield), time(atimefield), datetime(adatetimefield) from atable;
If however you want to make sure that the fields only contain exactly a date,time or datetime and you're inserting from variables, then you can
insert into atable values(date(thedate),time(thedate),datetime(thedate));
Sqlites typelessness makes some things really easy, but can confuse or complicate some other things.

Resources