How to write a program to print the wishes based on the sys time? - plsql

In PL/SQL Block, I would like to print the 'Good Morning','Good Noon','Good Eve' based on the system time that I have given as input.
If the time is 6 AM to 12 PM then it has to print GOOD MORNING
else if
it lies between 12 PM to 2 PM
it has to print GOOD NOON
else if it has to print GOOD EVE. So anybody can give me the Idea?
Advance Thanks for everyone who gives me the guidance.

I think, you know how the anonymous block looks like (reminder below):
DECLARE
-- variables' / constants' / types' / etc. declarations
BEGIN
-- logic
END;
/
You can create DATE variables or constants as follows:
l_in_date <CONSTANT> DATE := TO_DATE(<date>,<date_mask>);
Then you can use IF..THEN statement and print out the result according to the conditions (http://www.techonthenet.com/oracle/loops/if_then.php):
IF <condition> THEN
-- logic
ELSIF <condition> THEN
-- logic
ELSE
-- logic
END IF;
I believe, you should be able to create your anonymous block easily using the information above.

You could make a procedure or function that looks what time it is from the 24 hour format.
SELECT TO_CHAR(SYSDATE, HH24:MI:SS') INTO sysDate FROM dual;
Here sysDate is the current time in 24 hour format.
Then look if a time is within a certain timespan.

Related

SQLITE selecting distinct entries that are less than 1 minute old

I'm making a flight tracking map that will need to pull live data from a sql lite db. I'm currently just using the sqlite executable to navigate the db and understand how to interact with it. Each aircraft is identified by a unique hex_ident. I want to get a list of all aircraft that have sent out a signal in the last minute as a way of identifying which aircraft are actually active right now. I tried
select distinct hex_ident, parsed_time
from squitters
where parsed_time >= Datetime('now','-1 minute')
I expected a list of 4 or 5 hex_idents only but I'm just getting a list of every entry (today's entries only) and some are outside the 1 minute bound. I'm new to sql so I don't really know how to do this yet. Here's what each entry looks like. The table is called squitters.
{
"message_type":"MSG",
"transmission_type":8,
"session_id":"111",
"aircraft_id":"11111",
"hex_ident":"A1B4FE",
"flight_id":"111111",
"generated_date":"2021/02/12",
"generated_time":"14:50:42.403",
"logged_date":"2021/02/12",
"logged_time":"14:50:42.385",
"callsign":"",
"altitude":"",
"ground_speed":"",
"track":"",
"lat":"",
"lon":"",
"vertical_rate":"",
"squawk":"",
"alert":"",
"emergency":"",
"spi":"",
"is_on_ground":0,
"parsed_time":"2021-02-12T19:50:42.413746"
}
Any ideas?
You must remove 'T' from the value of parsed_time or use datetime() for it also to make the comparison work:
where datetime(parsed_time) >= datetime('now', '-1 minute')
Note that datetime() function does not take into account microseconds, so if you need 100% accuracy, you must put them in the code with concatenation:
where replace(parsed_time, 'T', ' ') >=
datetime('now', '-1 minute') || substr(parsed_time, instr(parsed_time, '.'))

Convert into am / pm in Impala

Like in a similar query on this forum I need, but I need it to work in Impala:
In a workaround my colleague and myself attempted the following:
-- combine start date and time into a datetime
-- impala can't handle am/pm so need to look for pm indicator and add 12 hours
-- and then subtract 12 hours if it's 12:xx am or pm
================
t1.appt_time,
hours_add(
to_timestamp(concat(to_date(t1.appt_date),' ',t1.appt_time),'yyyy-MM-dd H:mm'),
12*decode(lower(strright(t1.appt_time,2)),"pm",1,0) -
12*decode(strleft(t1.appt_time,2),'12',1,0)
) as appt_datetime,
t1. ...
=========
Has anybody an easier and more elegant approach ?
Your workaround is valid, Impala does currently support AM/PM formatting for dates. There are a few open issues related
https://issues.apache.org/jira/browse/IMPALA-3381
https://issues.apache.org/jira/browse/IMPALA-5237
https://issues.apache.org/jira/browse/IMPALA-2262

pljson_util_pkg sql_to_json doesn't work if values are less than 1

I have a problem with pljson_util_pkg.sql_to_json
declare
-- Local variables here
tstjson_list pljson_list;
l_Result_json_clob clob;
begin
-- Test statements here
tstjson_list := pljson_list();
dbms_lob.createtemporary(l_Result_json_clob, true);
tstjson_list := pljson_util_pkg.sql_to_json('SELECT 0.1 as tmp from dual');
tstjson_list.to_clob(l_Result_json_clob);
end;
When I execute this code I am getting error message:
Scanner problem with the following input: {"ROWSET":{"ROW":{"TMP":.1}}}
It looks like that if value is less than 1, then this error occurs because instead of 0.1 the result is .1!
Any idea why?
Thank you,
Zoran
Already closed, sorry
I think the reason is how oracle handle numbers in xml...
If you try this:
select xmlelement("tmp",0.1) from dual
you're going to receive the same result...
So, in order to achieve your gol just format the number via to_char function:
select xmlelement("tmp",to_char(0.1,'FM0.00')) from dual
Bye
Nicola

Problems about DECLARE Block contains a commented dynamic input variable

I am just new to PL/SQL.
I wrote a block to calculate the radius and circumference of a circle like below:
SET SERVEROUTPUT ON;
CREATE OR REPLACE PROCEDURE cal_circle AS
-- DECLARE
pi CONSTANT NUMBER := 3.1415926;
radius NUMBER := 3;
-- to make it more dynamic I can set
-- radius NUMBER := &enter_value;
circumference DECIMAL(4,2) := radius * pi * 2;
area DECIMAL(4,2) := pi * radius ** 2;
BEGIN
-- DBMS_OUTPUT.PUT_LINE('Enter a valur of radius: '|| radius);
dbms_output.put_line('For a circle with radius '
|| radius
|| ',the circumference is '
|| circumference
|| ' and the area is '
|| area
|| '.');
END;
/
Here you could see that I've commented the declare code radius NUMBER := &enter_value;, however, when I run my scripts in SQL*Plus or SQL Developer, I always got popup message like please enter the value for enter_value.
Oppositely, what if I delete this comment in the declare and just put it outside of it, then there will be no prompt anymore.
SET SERVEROUTPUT ON;
/* to make it more dynamic, I can set
radius NUMBER := &enter_value;
*/
CREATE OR REPLACE PROCEDURE cal_circle AS
-- DECLARE
pi CONSTANT NUMBER := 3.1415926;
radius NUMBER := 3;
circumference DECIMAL(4,2) := radius * pi * 2;
area DECIMAL(4,2) := pi * radius ** 2;
BEGIN
......
Here I want to clarify that does it mean the DECLARE block cannot accept comment when I try to comment a dynamic variable?
Thanks.
You can use a parameter instead of a substitution variable to allow different users to call the procedure with different values of pi.
I'd recommend using a FUNCTION instead of a PROCEDURE for this, but here's an example (Also using a parameter for radius). :
CREATE OR REPLACE PROCEDURE CAL_CIRCLE(P_RADIUS IN NUMBER, P_PI IN NUMBER) AS
CIRCUMFERENCE DECIMAL(4, 2) := P_RADIUS * P_PI * 2;
AREA DECIMAL(4, 2) := P_PI * P_RADIUS ** 2;
BEGIN
DBMS_OUTPUT.put_line('For a circle with radius '
|| P_RADIUS
|| ',the circumference is '
|| CIRCUMFERENCE
|| ' and the area is '
|| AREA
|| '.' || 'Calculated with Pi=: ' || P_PI);
END;
/
Then try it out:
BEGIN
CAL_CIRCLE(3, 3.14);
END;
/
For a circle with radius 3,the circumference is 18.84 and the area is
28.26.Calculated with Pi=: 3.14
BEGIN
CAL_CIRCLE(3, 3.14159);
END;
/
For a circle with radius 3,the circumference is 18.85 and the area is
28.27.Calculated with Pi=: 3.14159
If you really need to actually COMPILE the procedure with different values for its constants (not recommended) with a substituted value of pi, you can set the substitution variable first with DEFINE. like DEFINE pi_value = 3.1415;, then using &pi_value later.
Update: Why do SQLPlus and SQL Developer detect the Substitution Variable and request a value for it, even when it is in a comment?
TLDR: SQL Clients must deliver comments to the server. Preprocessing substitutions in comments gives greater flexibility and keeps the SQL Clients simpler. The clients have good support for controlling substitution behavior. There is not much of a reason to have orphan substitution variables in finalized code.
Longer-Version:
These tools are database clients--they have lots of features but first and foremost their first job is to gather input SQL, deliver it to the database server and handle fetched data.
Comments need to be delivered to the database server with their accompanying SQL statements. There are reasons for this -- so users can save comments on their compiled SQL code in the database, of course, but also for compiler hints.
Substitution Variables are not delivered with the SQL to the server like comments are. Instead they are evaluated first, and the resultant SQLText is sent to the server. (You can see the SQL that gets into the server has its Substitution Variables replaced with real values. See V$SQLTEXT).
Since the server "makes use" of the comments, it makes things more flexible and simplifies things for SQLPlus to replace the Substitution Variables even in comments. (If needed this can be overridden. I'll show that below). SQLPlus,SQLDeveloper, etc could have been designed to ignore Substitution Variables in comments, but that would make them less flexible and perhaps require more code since they would need to recognize comments and change their behavior accordingly, line-by-line. I'll show some example of this flexibility further below.
There is not much of a drawback to the tools working this way.
Suppose one just wants to ignore a chunk of code for a minute during development and quickly run everything. It would be annoying if one had DEFINE everything even though it wasn't used, or to delete all the commented code just so it could run. So these tools instead allow you to SET DEFINE OFF; and ignore the variables.
For example, this runs fine:
SET DEFINE OFF;
--SELECT '&MY_FIRST_IGNORED_VAR' FROM DUAL;
-- SELECT '&MY_SECOND_IGNORED_VAR' FROM DUAL;
SELECT 1919 FROM DUAL;
If one needs to use '&' itself in a query, SQLPlus lets you choose another character as the substitution marker. There are lots of options to control things.
If one has finished developing one's final query or procedure, it isn't a valid situation to have leftover "orphan" comments with undefined-substitutions. When development is complete, orphan substitutions should all be removed, and anything remaining should reference valid DEFINEd variables.
Here's an example that make use of processing substitutions in comments.
Suppose you wanted to tune some poor-performing SQL. You could use a substitution variable in the HINTs (in a comment) to allow for quickly changing which index is used, or execution mode, etc. without needing to actually change the query script.
CREATE TABLE TEST_TABLE_1(TEST_KEY NUMBER PRIMARY KEY,
TEST_VALUE VARCHAR2(128) NOT NULL,
CONSTRAINT TEST_VALUE_UNQ UNIQUE (TEST_VALUE));
INSERT INTO TEST_TABLE
SELECT LEVEL, 'VALUE-'||LEVEL
FROM DUAL CONNECT BY LEVEL <= 5000;
Normally a query predicating against TEST_VALUE here would normally use its UNIQUE INDEX when fetching the data.
SELECT TEST_VALUE FROM TEST_TABLE WHERE TEST_VALUE = 'VALUE-1919';
X-Plan:
------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 66 | 1 (0)| 00:00:01 |
|* 1 | INDEX UNIQUE SCAN| TEST_VALUE_UNQ | 1 | 66 | 1 (0)| 00:00:01 |
------------------------------------------------------------------------------------
But one can force a full-scan via a hint. By using a substitution variable in the hint (in a comment), one can allow the values of the Substitution Variable to direct query-execution:
DEFINE V_WHICH_FULL_SCAN = 'TEST_TABLE';
SELECT /*+ FULL(&V_WHICH_FULL_SCAN) */ TEST_VALUE FROM TEST_TABLE WHERE TEST_VALUE = 'VALUE-1919';
Here the Substitution Variable (in its comment) has changed the query-execution.
X-Plan:
--------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
--------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 23 | 1518 | 9 (0)| 00:00:01 |
|* 1 | TABLE ACCESS FULL| TEST_TABLE | 23 | 1518 | 9 (0)| 00:00:01 |
--------------------------------------------------------------------------------
If there were a bunch of tables here instead of one, a person could DEFINE different targets to full-scan, and evaluate each impact on the query quickly.

how to guess random values from user in pl sql

could someone help?
declare
ran int:=dbms_random.value(1,5);
num number;
begin
dbms_output.put_line('enter the num');
num:=&num;
if num<ran then
&dbms_output.put_line('Your num is less'||ran);
elsif num>ran then
&dbms_output.put_line('Your num is greater'||ran);
else
&dbms_output.put_line('Equal'||num||'='||ran);
end if;
while num=ran loop
&dbms_output.put_line('enter the num');
num:=&num;
end loop;
end;
there is some problems ?
what is wrong?
how to guess random numbers what's wrong
You would need to prompt for the number separately, and then use the value in a PL/SQL block once you have it.
Substitution variables are a SQL*Plus feature and not part of the core PL/SQL language (which is not interactive), so the following works in SQL*Plus. Client applications such as PL/SQL Developer emulate it to varying degrees, so it may also work in those (for example in PL/SQL Developer you would run it in a Command window, or in TOAD you'd use the 'Run as script' option). You may also be able to do something in Apex or using a third party scripting language such as Perl, Python, PowerShell etc.
accept mynumber number format 0 prompt "Enter a number between 1 and 5: "
declare
ran int := dbms_random.value(1, 5);
begin
if &mynumber < ran then
dbms_output.put_line('&mynumber is less than ' || ran);
elsif &mynumber > ran then
dbms_output.put_line('&mynumber is greater than ' || ran);
else
dbms_output.put_line('&mynumber = ' || ran);
end if;
end;
/
I'm not sure what the loop in your example is supposed to do. If you want it to prompt for input repeatedly in a loop you will need to write something in a separate scripting language or another development framework.

Resources