SQL Code for Running Total does not recognise table name - ms-access-2010

I have a question on creating running totals in MS Access 2010 similar to the one here:
Access 2010 - query showing running total for multiple records, dropping old record and adding new record on each line
However when I input the equivalent code from that thread I get an error saying that the database cannot be found (Access seems to think the table I have specified is the database name)
Here is the code from the original thread:-
SELECT hbep1.EmployeeID, hbep1.PayPeriodID,
(
SELECT Sum(hbep2.HoursUsed)
FROM Hours_by_Empl_PP hbep2
WHERE hbep2.EmployeeID=hbep1.EmployeeID
AND (hbep2.PayPeriodID Between hbep1.[PayPeriodID]-3
And hbep1.[PayPeriodID])
) AS Sum_of_Hours_last_4_PPs
FROM Hours_by_Empl_PP hbep1;
Here is the code I inputted into my query:-
SELECT
V4_Try.ID_NIS_INV_HDR,
V4_Try.ID_ITM,
V4_Try.RunTot3,
V4_Try.BomVsActQty,
DMin("RunTot3","V4_Try","[ID_Itm]=" & [ID_ITM]) AS IDItmMin,
DMax("RunTot3","V4_Try","[ID_Itm]=" & [ID_ITM]) AS IDItmMax,
(
SELECT Sum([V4_Try].[BomVsActQty])
FROM [V4_Try].[BomVsActQty]
WHERE [V4_Try].[ID_ITM]=[V4_Try].[ID_ITM]
AND (IDItmMax < IDItmMin)
) AS RunTot6
FROM V4_Try
ORDER BY V4_Try.ID_ITM, V4_Try.RunTot3;

One thing I notice is that the main query uses DMax() and DMin() to create some aliased columns
...
DMin("RunTot3","V4_Try","[ID_Itm]=" & [ID_ITM]) AS IDItmMin,
DMax("RunTot3","V4_Try","[ID_Itm]=" & [ID_ITM]) AS IDItmMax,
...
and then the subquery tries to use those aliases in its WHERE clause
(
SELECT ...
WHERE...
AND (IDItmMax < IDItmMin)
) AS RunTot6
I'm pretty sure that the subquery will have no knowledge of the column aliases in the "parent" query, so they may be the items that are unrecognized.

Start by running this query:
SELECT * FROM V4_Try;
Then develop for complexity. Build the nested query before anything else. When you know that runs, try adding your aliases, then the DMax() function, and so on. Isolate the point at which you have an error popping up.
This is the process to fix a query.
Oh, and please specify the precise error that is raised by Access. Also, if this is being run from VBA, please let us know because that affects your trouble-shooting.

Related

age control 2 for pl/sql

i am trying to find out at what age an employee started working.
if he started under 16 he should report this 'Error when entering the date of birth' mistake. so my trigger is created but my trigger is not working
I get ever this error: ORA-01422: Exact retrieval returns more than the requested number of lines
i can't find the problem
Here is the code:
SET SERVEROUTPUT ON
ACCEPT Birthday PROMPT ' Pleas give you Date of birth: '
CREATE OR REPLACE TRIGGER T_Controll
before INSERT ON meine_Firma -- Table
FOR EACH ROW
DECLARE
V_Berufstart meine_Firma.Hiredate%TYPE; --Job begin
V_Geburtsdatum DATE; -- Date of birth
V_Alter number:=0; -- AGE
SELECT HIREDATE INTO V_Berufstart FROM meine_Firma;
BEGIN
V_Geburtsdatum:=('&Birthday');
V_Alter:= Round(MONTHS_BETWEEN(V_Berufstart,V_Geburtsdatum)-2)/12;
IF 16 > V_Alter THEN
RAISE_APPLICATION_ERROR(-20201,'Error when entering the date of birth');
END IF;
END;
/
SET SERVEROUTPUT OFF
If he under 16 then he may not work
sorry my english is not good (=
You have a much bigger issue in this script than the error you are getting. Even after correcting as #ShaunPeterson suggested it will still fail
, it WILL NOT generate an error it will just not run as you expect. The issue is you failed to understand substitution variables - the use of &name (Specifically here &Birthday.) I'll actually use &Birthday in the following but the discussion applies to ANY/ALL substitution variables.
people fail to understand why they can't use the "&" substitution
variables in their PL/SQL procedures and functions to prompt for input
at run time. This article will hopefully help clarify in your mind
what the differences are so that you can understand where and when to
use these.
Substitution Variables The clue here is in the name... "substitution". It relates to values being substituted into the code
before it is submitted to the database. These substitutions are
carried out by the interface being used
The effect of this substitution is the the line containing the substitution variable is physically rewritten by the interface replacing %Birthday. In this case if you don't enter a value or the date 2000-05-19 the statement before and after substitution is
BEFORE: V_Geburtsdatum:=('&Birthday');
AFTER: V_Geburtsdatum:=(''); OR V_Geburtsdatum:=('2000-05-19');
Either way the after is what the compiler sees; it does NOT see %Birthday at all. Moreover when run the trigger will not prompt for a value. As far as the compiler is concerned it is a hard coded value that will never change. Beyond that a trigger, or any other PLSQL script (stored or anonymous) never prompts for values, they are actually incapable of doing so as it is not part of the language. Any prompt is via your interface software not plsql.
I'm going to suggest a way to avoid the trigger altogether. Getting on soap box: Triggers are BAD, they have some usefulness for assigning auto incrementing keys (before 12c),logging, very limited auditing, etc. However, for business rules they should be the option of last resort. Ok Get off soap box.
The first thing is to make the columns meine_Firma.Hiredate and meine_Firma.Geburtsdatum NOT null (if not already). If either are NULL you cannot calculate anything with them, the result would be NULL.
Second create a new column age_at_hire (or whatever) as a virtual column then put a check constraint on it. And voila trigger no longer needed. See fiddle for demo.
So the proposed change (YES you will probably have to clean up the bad data first):
alter table meine_Firma modify
( hiredate not null
, Geburtsdatum not null
) ;
alter table meine_Firma add
( age_at_hire integer generated always as (trunc(months_between(hiredate,Geburtsdatum))) virtual
, constraint check_age_at_hire check (age_at_hire >= 16*12)
);
Anyway, I hope you get an understanding of substitution variables for the future. And learn to avoid triggers. Good luck.
The reason you are getting that specific error is that the below select will select ALL rows from meine_Firma as there is no where clause
SELECT HIREDATE INTO V_Berufstart FROM meine_Firma;
However because you are in a trigger you do not need to select anything you use the :NEW bind variable. So you can just use
V_Berufstart := :NEW.HIREDATE;
If this was an update trigger there would be both a :NEW and :OLD bind variable declared so that you can access the OLD and NEW values. As this is an Insert trigger the :OLD will just be null as there is no old values.

Error with SQLite query, What am I missing?

I've been attempting to increase my knowledge and trying out some challenges. I've been going at this for a solid two weeks now finished most of the challenge but this one part remains. The error is shown below, what am i not understanding?
Error in sqlite query: update users set last_browser= 'mozilla' + select sql from sqlite_master'', last_time= '13-04-2019' where id = '14'
edited for clarity:
I'm trying a CTF challenge and I'm completely new to this kind of thing so I'm learning as I go. There is a login page with test credentials we can use for obtaining many of the flags. I have obtained most of the flags and this is the last one that remains.
After I login on the webapp with the provided test credentials, the following messages appear: this link
The question for the flag is "What value is hidden in the database table secret?"
So from the previous image, I have attempted to use sql injection to obtain value. This is done by using burp suite and attempting to inject through the user-agent.
I have gone through trying to use many variants of the injection attempt shown above. Im struggling to find out where I am going wrong, especially since the second single-quote is added automatically in the query. I've gone through the sqlite documentation and examples of sql injection, but I cannot sem to understand what I am doing wrong or how to get that to work.
A subquery such as select sql from sqlite_master should be enclosed in brackets.
So you'd want
update user set last_browser= 'mozilla' + (select sql from sqlite_master''), last_time= '13-04-2019' where id = '14';
Although I don't think that will achieve what you want, which isn't clear. A simple test results in :-
You may want a concatenation of the strings, so instead of + use ||. e.g.
update user set last_browser= 'mozilla' || (select sql from sqlite_master''), last_time= '13-04-2019' where id = '14';
In which case you'd get something like :-
Thanks for everyone's input, I've worked this out.
The sql query was set up like this:
update users set last_browser= '$user-agent', last_time= '$current_date' where id = '$id_of_user'
edited user-agent with burp suite to be:
Mozilla', last_browser=(select sql from sqlite_master where type='table' limit 0,1), last_time='13-04-2019
Iterated with that found all tables and columns and flags. Rather time consuming but could not find a way to optimise.

PL/SQL Oracle Stored Procedure (No Data Found)

CODE
-- Stored Procedure
CREATE OR REPLACE PROCEDURE DEVELOPMENT_PROCEDURE
(
P_JOB_TYPE IN JOBS.JOB_TITLE%type DEFAULT 'Manager'
, P_JOB_ID OUT JOBS.JOB_ID%type
, P_JOB_TITLE OUT JOBS.JOB_TITLE%type
) AS
BEGIN
SELECT JOB_ID, JOB_TITLE
INTO P_JOB_ID, P_JOB_TITLE
FROM JOBS
WHERE JOB_TITLE = P_JOB_TYPE;
END DEVELOPMENT_PROCEDURE;
CODE
-- Calling the Stored Procedure
DECLARE
P_JOB_ID JOBS.JOB_ID%type;
P_JOB_TITLE JOBS.JOB_TITLE%type;
P_JOB_TYPE VARCHAR2(25) := 'Manager';
BEGIN
DEVELOPMENT_PROCEDURE(P_JOB_TYPE,P_JOB_ID,P_JOB_TITLE);
SYS.DBMS_OUTPUT.PUT_LINE(P_JOB_ID);
SYS.DBMS_OUTPUT.PUT_LINE(P_JOB_TITLE);
END;
Problem
This is the error message I am receiving after running. I am following a tutorial to the letter, but still receiving errors; solved most ... stuck here.
ORA-01403: no data found
ORA-06512: at "HR.DEVELOPMENT_PROCEDURE", line 8
ORA-06512: at line 8
There is no exception setup, but I should be seeing 15 records. Any ideas?
Could this be an issue with declaration? I need the parameter to read Manager and not MANAGER. Could this be the issue? If so, how can I fix it so the variable read like Manager. Thank you.
As #Drumbeg had pointed out, I am actually pulling too many records, but even after fixing SQL to select single record I am still receiving same error. Could there be an issue with the database itself?
From the comments above, I think we can deduce there is a difference in case between P_JOB_TYPE and the JOB_TYPE data for your expected rows in the database, hence why applying lower() to both sides of the predicate starts to bring data back.
It's worth pointing out that applying a lower() to both sides of the predicate is not a good solution on it's own as there may be performance implications if this is not supported by a functional index. Probably better to be sure of the case you are storing in the database and just apply an upper() or lower() to the right hand side of the predicate (i.e. P_JOB_TYPE side).

RowCount,Table must Exist, Delete All Rows from Table keywords from Robotframework

I am new to robotframework and I am trying to get the hang of the keywords of DatabaseLibrary. I am getting error at 3 of such keywords.
1) I am using rowcount keywords as below-
${rowCount} Row Count <sql query>
And I always get ${rowCount}=0 irrespective of the number of rows in my table.
2) I am using Delete All Rows From Table as below-
Delete All Rows From Table <Table_Name>
And I get ORA-00911: invalid character but if use the same table with other keywords like Query ,it works fine.
3) I am using Table Must Exist as below-
Table Must Exist <Table_Name>
And I get ORA-00942: table or view does not exist but this table is very much there.
Please help me find what am I doing wrong.
Thanks in Advance!!!
I could be wrong but I believe a colleague told me there were issues, at the very least with the Row Count keyword.
However, for all three options there are easy solutions, which you've even hinted at in your question by using Query or Execute SQL Script
1)
${result}= Query Select count(id) from table
${rc} = ${result[0][0]} #Play with this as I forget exact syntax
2) Put your delete script in a test scripts folder with your tests and call it using Execute SQL script. You could also use Query to perform a select query before and after to confirm expected states.
3) Again perform a query against the table you're expecting to be there, a simple row count on id would do for this purpose. You could set a variable based on the result and use this again later if required.
I had similar issues.
I use cx_Oracle.
With the Table Must Exist keyword my problem was the same.
I dont really understand why, but first I have to use Encode String to Bytes keyword.
And I need to use a DatabaseLibrary 0.8 at least, because earlier versions didnt have solution for cx_Oracle. These solved this issue for me.
But with Delete all rows from table I still have problems.
Because this keyword puts a ; at the end of the line and it passes on that line to execute query if I understand weel, so it still causes an ORA-00911 error for me.
With Execute Sql String and the command DELETE FROM tablename you can have the same results, but it will work this way.
I hope it helps a little

How to find out which package/procedure is updating a table?

I would like to find out if it is possible to find out which package or procedure in a package is updating a table?
Due to a certain project being handed over (the person who handed over the project has since left) without proper documentation, data that we know we have updated always go back to some strange source point.
We are guessing that this could be a database job or scheduler that is running the update command without our knowledge. I am hoping that there is a way to find out where the source code is calling from that is updating the table and inserting the source as a trigger on that table that we are monitoring.
Any ideas?
Thanks.
UPDATE: I poked around and found out
how to trace a statement back to its
owning PL/SQL object.
In combination with what Tony mentioned, you can create a logging table and a trigger that looks like this:
CREATE TABLE statement_tracker
( SID NUMBER
, serial# NUMBER
, date_run DATE
, program VARCHAR2(48) null
, module VARCHAR2(48) null
, machine VARCHAR2(64) null
, osuser VARCHAR2(30) null
, sql_text CLOB null
, program_id number
);
CREATE OR REPLACE TRIGGER smb_t_t
AFTER UPDATE
ON smb_test
BEGIN
INSERT
INTO statement_tracker
SELECT ss.SID
, ss.serial#
, sysdate
, ss.program
, ss.module
, ss.machine
, ss.osuser
, sq.sql_fulltext
, sq.program_id
FROM v$session ss
, v$sql sq
WHERE ss.sql_address = sq.address
AND ss.SID = USERENV('sid');
END;
/
In order for the trigger above to compile, you'll need to grant the owner of the trigger these permissions, when logged in as the SYS user:
grant select on V_$SESSION to <user>;
grant select on V_$SQL to <user>;
You will likely want to protect the insert statement in the trigger with some condition that only makes it log when the the change you're interested in is occurring - on my test server this statement runs rather slowly (1 second), so I wouldn't want to be logging all these updates. Of course, in that case, you'd need to change the trigger to be a row-level one so that you could inspect the :new or :old values. If you are really concerned about the overhead of the select, you can change it to not join against v$sql, and instead just save the SQL_ADDRESS column, then schedule a job with DBMS_JOB to go off and update the sql_text column with a second update statement, thereby offloading the update into another session and not blocking your original update.
Unfortunately, this will only tell you half the story. The statement you're going to see logged is going to be the most proximal statement - in this case, an update - even if the original statement executed by the process that initiated it is a stored procedure. This is where the program_id column comes in. If the update statement is part of a procedure or trigger, program_id will point to the object_id of the code in question - you can resolve it thusly:
SELECT * FROM all_objects where object_id = <program_id>;
In the case when the update statement was executed directly from the client, I don't know what program_id represents, but you wouldn't need it - you'd have the name of the executable in the "program" column of statement_tracker. If the update was executed from an anonymous PL/SQL block, I'm not how to track it back - you'll need to experiment further.
It may be, though, that the osuser/machine/program/module information may be enough to get you pointed in the right direction.
If it is a scheduled database job then you can find out what scheduled database jobs exist and look into what they do. Other things you can do are:
look at the dependencies views e.g. ALL_DEPENDENCIES to see what packages/triggers etc. use that table. Depending on the size of your system that may return a lot of objects to trawl through.
Search all the database source code for references to the table like this:
select distinct type, name
from all_source
where lower(text) like lower('%mytable%');
Again that may return a lot of objects, and of course there will be some "false positives" where the search string appears but isn't actually a reference to that table. You could even try something more specific like:
select distinct type, name
from all_source
where lower(text) like lower('%insert into mytable%');
but of course that would miss cases where the command was formatted differently.
Additionally, could there be SQL scripts being run through "cron" jobs on the server?
Just write an "after update" trigger and, in this trigger, log the results of "DBMS_UTILITY.FORMAT_CALL_STACK" in a dedicated table.
The purpose of this function is exactly to give you the complete call stack of al the stored procedures and triggers that have been fired to reach your code.
I am writing from the mobile app, so i can't give you more detailed examples, but if you google for it you'll find many of them.
A quick and dirty option if you're working locally, and are only interested in the first thing that's altering the data, is to throw an error in the trigger instead of logging. That way, you get the usual stack trace and it's a lot less typing and you don't need to create a new table:
AFTER UPDATE ON table_of_interest
BEGIN
RAISE_APPLICATION_ERROR(-20001, 'something changed it');
END;
/

Resources