Declaring a variable in sql - sql

Im sorry about the mess but what I'm trying to do is create a variable for ops$u2970. I've tried some ways that I found online and they did not work. This is part of a much larger query so replacing ops$u2970 with a variable would be great especially since it will need to be changed in the future throughout the query. This is easy in Python, but alas this is sql.
--***Creates a VIEW of all TIS GN's with their Corridor ID, Accum Mile and XY coords
create or replace view GN_DC_LOCATE as
select distinct t.gn_id, n.tcr_rt||n.tcr_rb DC_ID,
case when n.beg_brkm<n.end_brkm then
round(((t.gn_km-n.beg_brkm)+n.beg_tcrkm)*.6213712,3)
else round(((n.beg_brkm-t.gn_km)+n.beg_tcrkm)*.6213712,3)
end as GN_DCMI,c.x_coord TIS_XCOORD, c.y_coord TIS_YCOORD
from tis.tis_gn_locate t,tis.tis_tcr_lookup n,tis.tis_gn_coords c
where t.route=n.br_id and t.gn_km>=n.beg_abskm and t.gn_km<=n.end_abskm
and t.gn_id=c.gn_id
--***Creates a VIEW of all begin and end GN's on ops$u2087.sec_segments
--from the view GN_DC_LOCATE and adds in the records where GN=999999999999
create or replace view PVMGT_SEGS_GNs_DCMI as
select p.corridor_code_rb,
b.gn_id,b.GN_DCMI TIS_MI,
b.TIS_XCOORD TIS_X,b.TIS_YCOORD TIS_Y
from ops$u2970.sec_segments p, GN_DC_LOCATE b
where p.corridor_code_rb=b.DC_ID and p.beg_gn=b.gn_id
UNION
select p.corridor_code_rb,
e.gn_id,e.GN_DCMI TIS_MI,e.TIS_XCOORD TIS_X,e.TIS_YCOORD TIS_Y
from ops$u2970.sec_segments p,GN_DC_LOCATE e
where p.corridor_code_rb=e.DC_ID and p.end_gn=e.gn_id
UNION
select p.corridor_code_rb,999999999999 GN_ID, NULL TIS_MI,NULL TIS_X,NULL TIS_Y
from ops$u2970.sec_segments p
where p.beg_gn=999999999999 or p.end_gn=999999999999
order by 1,3

It's not possible to use variables in Oracle VIEW definitions. Variables are allowed in stored procedures, functions, triggers and packages.

Related

Want to create user-accessible form in Axapta that uses SQL with a substring function

I have some sqlserver sql that due to data can't be modified, which I currently run from Sqlserver. It uses a substring function. I want to stop running it from Sqlserver and create a user-accessible form in which the user enters a date and the script goes off and does it's thing and returns row data to the user.
Not overly familar with X++. I've looked at reports, querys, jobs, statement classes, not sure what's the correct path.
Below is the sql code.
'
select a.description,b.itemid, c.phantom,a.createddatetime,a.createdby
from sysdatabaselog A
inner join
bomversion B
on substring(a.description,1,11) = b.bomid
inner join
inventtable C
on b.itemid = c.itemid
where (table_ = 18 and logtype=1)
and a.CREATEDDATETIME > '2018-03-01' <-------- this would be user-supplied on the form
and c.phantom=1
'
What you're trying to accomplish is actually pretty high-level in AX and requires a several different dev techniques to accomplish it. I'm not going to do the entire thing for you, but I'll get you started and tell you what you need to do. These screenshots are from AX2012.
To accomplish the SUBSTRING() you need an AX View + String computed column.
For your view, you'll want an AX Query object to contain your joins OR you can just do a simple view on the BOMVersion table and then work against that.
Here's an example View and String computed column and the method for the computed column. I just used SalesTable and SalesId as the sample.
public static server str compSubStrSalesName()
{
str result;
result = strFmt("SUBSTRING(%1, 1, 5)",
SysComputedColumn::returnField(identifierStr(SubStringExample), // The name of your view
identifierStr(SalesTable_1), // The name of your view's datasource
identifierStr(SalesId) // The name of the field
)
);
return result;
}

Like Clause over an 'Element' - ORACLE APEX

I encounter some problems that i don't understand with APEX.... Well, let's be specific.
I ve got a select element retrieving a top 50 of most liked url (P11_URL). This is populate by a table view, TOp_Domains.
I create an element called "Context" that have to print all text containing the URL selected by the user from the element select. Those Texts come from another table, let's say "twitter_post".
I create a dynamic action (show only) with this sql/statement:
Select TXT, NB_RT, RANK
from myschema.twitter_post
where TXT like '%:P11_URL%'
group by TXT, NB_RT, RANK
.... and it doesn't work... I think APEX don't like like clause... But i don't know how to do. Let's keep in min an url could have been shared by multiple Tweets, that's why this element "context" is important for me.
I tried to bypass the problem by building a State (in french Statique) and a dynamic action that will refresh the state but it doesn't work neither... bouhououououou
TriX
Right click on the 'P11_URL' and create DA. Event :change, Item:P11_URL. As the true action of the DA, select 'Set Value'. Write your query in the sql stmt area. In the page items to submit, select 'P11_URL' . In the 'Affected Items': select 'Context'.
Query should be :
Select TXT, NB_RT, RANK
from myschema.twitter_post
where TXT like '%' || :P11_URL || '%'
group by TXT, NB_RT, RANK
So
Thanks to #Madona... Their example made me realised my mistake. I wrote the answer here for futher help if somebody encouter the same porblem.
A list select element get as arguments a display value (the one you want to be shown in your screen.... if you want so....^^ ) and a return value (in order, I think to linked dynamic actions). So to solved my problem i had to shape my sql statement as:
select hashtags d, hastags r
from my table
order by 1
[let s say that now in Apex it s an object called P1_HASHTAGS]
First step problem solving.
In fact, the ranking as second value, as i put into my sql statement was making some mitsakens into my 'Where like' clause search... well... Newbie am i!
Second step was to correctly formate the sql statement receiving the datas from my select lov (P1_HASHTAGS) into my interactive report. As shown here:
Select Id, hashtags
from my table
where txt like '%'||:P1_HASHTAGS||'%'
And it works!
Thank you Madona your example helped me figure my mistakes!

Syntax error on WITH clause

I am working on a web app and there are some long winded stored procedures and just trying to figure something out, I have extracted this part of the stored proc, but cant get it to work. The guy who did this is creating alias after alias.. and I just want to get a section to work it out. Its complaining about the ending but all the curly brackets seem to match. Thanks in advance..
FInputs is another stored procedure.. the whole thing is referred to as BASE.. the result of this was being put in a temp table where its all referred to as U. I am trying to break it down into separate sections.
;WITH Base AS
(
SELECT
*
FROM F_Inputs(1,1,100021)
),
U AS
(
SELECT
ISNULL(q.CoverPK,r.CoverPK) AS CoverPK,
OneLine,
InputPK,
ISNULL(q.InputName,r.InputName) AS InputName,
InputOrdinal,
InputType,
ParentPK,
InputTriggerFK,
ISNULL(q.InputString,r.InputString) AS InputString,
PageNo,
r.RatePK,
RateName,
Rate,
Threshold,
ISNULL(q.Excess,r.Excess) AS Excess,
RateLabel,
RateTip,
Refer,
DivBy,
RateOrdinal,
RateBW,
ngRequired,
ISNULL(q.RateValue,r.RateValue) AS RateValue,
ngClass,
ngPattern,
UnitType,
TableChildren,
TableFirstColumn,
parentRatePK,
listRatePK,
NewParentBW,
NewChildBW,
ISNULL(q.SumInsured,0) AS SumInsured,
ISNULL(q.NoItems,0) AS NoItems,
DisplayBW,
ReturnBW,
StringBW,
r.lblSumInsured,
lblNumber,
SubRateHeading,
TrigSubHeadings,
ISNULL(q.RateTypeFK,r.RateTypeFK) AS RateTypeFK,
0 AS ListNo,
0 AS ListOrdinal,
InputSelectedPK,
InputVis,
CASE
WHEN ISNULL(NewChildBW,0) = 0
THEN 1
WHEN q.RatePK is NOT null
THEN 1
ELSE RateVis
END AS RateVis,
RateStatus,
DiscountFirstRate,
DiscountSubsequentRate,
CoverCalcFK,
TradeFilter,
ngDisabled,
RateGroup,
SectionNo
FROM BASE R
LEFT JOIN QuoteInputs Q
ON q.RatePK = r.RatePK
AND q.ListNo = 0
AND q.QuoteId = 100021 )
Well, I explained the issue in the comments section already. I'm doing it here again, so future readers find the answer more easily.
A WITH clause is part of a query. It creates a view on-the-fly, e.g.:
with toys as (select * from products where type = 'toys') select * from toys;
Without the query at the end, the statement is invalid (and would not make much sense anyhow; if one wanted a permanent view for later use, one would use CREATE VIEW instead).

Apex parse error when creating SQL query with sql function

I have the following function:
CREATE OR REPLACE FUNCTION calc_a(BIDoctor number) RETURN number
IS
num_a number;
BEGIN
select count(NAppoint)
into num_a
from Appointment a
where BIDoctor = a.BIDoctor;
RETURN num_a;
END calc_a;
What we want is adding a column to a report that shows us the number of appointments that doc have.
select a.BIdoctor "NUM_ALUNO",
a.NameP "Nome",
a.Address "Local",
a.Salary "salary",
a.Phone "phone",
a.NumberService "Curso",
c.BIdoctor "bi",
calc_media(a.BIdoctor) "consultas"
FROM "#OWNER#"."v_Doctor" a, "#OWNER#"."Appointment" c
WHERE a.BIdoctor = c.BIdoctor;
and we got this when we are writing the region source on apex.
But it shows a parse error, I was looking for this about 2 hours and nothing.
Apex shows me this:
PARSE ERROR ON THE FOLLOWING QUERY
This is probably because of all your double quotes, you seem to have randomly cased everything. Double quotes indicate that you're using quoted identifiers, i.e. the object/column must be created with that exact name - "Hi" is not the same as "hi". Judging by your function get rid of all the double quotes - you don't seem to need them.
More generally don't use quoted identifiers. Ever. They cause far more trouble then they're worth. You'll know when you want to use them in the future, if it ever becomes necessary.
There are a few more problems with your SELECT statement.
You're using implicit joins. Explicit joins were added in SQL-92; it's time to start using them - for your future career where you might interact with other RDBMS if nothing else.
There's absolutely no need for your function; you can use the analytic function, COUNT() instead.
Your aliases are a bit wonky - why does a refer to doctors and c to appointments?
Putting all of this together you get:
select d.bidoctor as num_aluno
, d.namep as nome
, d.address as local
, d.salary as salary
, d.phone as phone
, d.numberservice as curso
, a.bidoctor as bi
, count(nappoint) over (partition by a.bidoctor) as consultas
from #owner#.v_doctor a
join #owner#.appointment c
on d.bidoctor = a.bidoctor;
I'm guessing at what the primary keys of APPOINTMENT and V_DOCTOR are but I'm hoping they're NAPPOINT and BIDOCTOR respectively.
Incidentally, your function will never have returned the correct result because you haven't limited the scope of the parameter in your query; you would have just counted the number of records in APPOINTMENT. When you're naming parameters the same as columns in a table you have to explicitly limit the scope to the parameter in any queries you write, for instance:
select count(nappoint) into num_a
from appointment a
where calc_a.bidoctor = a.bidoctor; -- HERE

PostgreSQL view won't work - column doesnt exist

Hi I am trying to migrate an access database into postgresql and everything was going well until i tried this view. I am wanting it to create a new column called 'CalculatedHours'. And as Im new to postgresql I am slightly confused. Heres the code that I keep putting into pgAdmin and getting the error...
SELECT "SessionsWithEnrolmentAndGroups"."SessionID",
"Assignments"."Staff",
"SessionsWithEnrolmentAndGroups"."groups",
"SessionsWithEnrolmentAndGroups"."SessionQty",
"SessionsWithEnrolmentAndGroups"."Hours",
"SessionsWithEnrolmentAndGroups"."Weeks",
"Assignments"."Percentage",
"Assignments"."AdditionalHours",
Round((coalesce(("groups"),1)*("SessionQty")*("Hours")*("Weeks")
*("Percentage"))) AS CalculatedHours,
(CalculatedHours)+coalesce(("AdditionalHours"),0) AS "TotalHours"
FROM "SessionsWithEnrolmentAndGroups"
INNER JOIN "Assignments"
ON "SessionsWithEnrolmentAndGroups"."SessionID" = "Assignments"."SessionID";
You cannot access column aliases in the same select where they are defined. I would suggest a subquery:
SELECT t.*,
(CalculatedHours)+coalesce(("AdditionalHours"), 0) AS "TotalHours"
FROM (SELECT eag."SessionID", a, eag."groups", eag."SessionQty",
eag."Hours", eag."Weeks", a."Percentage", a."AdditionalHours",
Round((coalesce(("groups"),1)*("SessionQty")*("Hours")*("Weeks")*("Percentage"))) AS CalculatedHours
FROM "SessionsWithEnrolmentAndGroups" eag INNER JOIN
"Assignments" a
ON eag."SessionID" = a."SessionID"
) t;
Your queries would also be much more readable using table aliases and getting rid of the escape characters (double quotes) unless they are really, really needed.