I don't know how to verify if a parameter exists in the funcion or procedure - plsql

Design a table named "customs agencies" with the following fields: name, address, patent number, id_ customs agent. Where customs agent is another table with name and seniority.
Create a function or procedure that allows inserting new agencies and being able to edit an agency giving the ID of the customs agency.
I don't know how to do this: If id exists in parameter we do an update, else we insert new agencies.

Suppose parameter's name is PAR_ID; then you'd
create or replace procedure p_agency (par_id in agency.id%type,
par_name in agency.name%type
)
is
begin
if par_id is null then
insert into agency (id, name) values (par_id, par_name);
else
update agency set name = par_name
where id = par_id;
end if;
end;
If you wonder where are other columns - well, I'll leave that piece of homework to you.

Related

Oracle 11g Triggers

I have create a table person(id, name ,samenamecount).The samenamecount attribute can be null but for each row can store the row count for same names.I am achieving this by calling a stored procedure inside a after insert trigger.Below is my code.
create or replace procedure automatic(s in person.name%type)
AS
BEGIN
update person set samenamecount=(select count(*) from person where name=s) where name=s;
END;
create or replace trigger inserttrigger
after insert
on person
for each row
declare
begin
automatic(:new.name);
end;
On inserting a row it is giving error like
table ABCD.PERSON is mutating, trigger/function may not see it.
Can somebody help me to figure out this?
If you have the table:
CREATE TABLE person (
id NUMBER
GENERATED ALWAYS AS IDENTITY
CONSTRAINT person__id__pk PRIMARY KEY,
name VARCHAR2(20)
NOT NULL
);
Then rather than creating a trigger, instead, you could use a view:
CREATE VIEW person_view (
id,
name,
samenamecount
) AS
SELECT id,
name,
COUNT(*) OVER (PARTITION BY name)
FROM person;
You can use the trigger:
CREATE TRIGGER inserttrigger
AFTER INSERT ON person
BEGIN
MERGE INTO person dst
USING (
SELECT ROWID AS rid,
COUNT(*) OVER (PARTITION BY name) AS cnt
FROM person
) src
ON (src.rid = dst.ROWID)
WHEN MATCHED THEN
UPDATE SET samenamecount = src.cnt;
END;
/
fiddle
If you want to make it more efficient then you could use a compound trigger and collate the names that are being inserted and only update the matching rows.

SQLite using NEW in subquery in a trigger

I'm trying to create a trigger that classifies some news in my database by category after every insert on the table news if the attribute title contains "COVID-19" or "coronavirus" (then the category id should be the one with the name "COVID-19") or if the attribute title contains "Ukraine" or "Rusia" (then the category id should be the one with the name "War").
The tables have the following structure:
news (id, title, text, date, user(FK))
category (id, name, description)
new_cat(news(FK), category(FK))
And I tried implementing the following trigger without success:
CREATE TRIGGER news_categorizer AFTER INSERT ON news
FOR EACH ROW
BEGIN
INSERT INTO new_cat (news, category) VALUES (NEW.id,
(SELECT id from category WHERE name = "COVID-19" AND (NEW.title = "%COVID-19%" or NEW.title = "%coronavirus%")));
END;
How could I properly develop this subquery or can I do different INSERTs depending on a condition?
Use properly the operator LIKE in a CASE expression:
CREATE TRIGGER news_categorizer AFTER INSERT ON news
FOR EACH ROW
BEGIN
INSERT INTO new_cat (news, category)
SELECT NEW.id,
id
FROM category
WHERE name = CASE
WHEN (NEW.title LIKE '%COVID-19%') OR (NEW.title LIKE '%coronavirus%') THEN 'COVID-19'
WHEN (NEW.title LIKE '%Ukraine%') OR (NEW.title LIKE '%Rusia%') THEN 'War'
END;
END;
See a simplified demo.

PLSQL Array of Record to out parameter

I have a scenario where I need to return the following to frontend UI from PL/SQL procedure. Can you please help me with the logic and code.
The following query returns 2 column values, which I require to pass as 1 out parameter to the calling UI procedure:
SELECT emp.EMP_NAME,
dep.DEPT_NAME
FROM employee emp,
department dept
WHERE dept.DEPT_NO in emp.DEPT_NO
If you want to use department name as argument to provide the employees name associated with that department, you can use it with the function.
create or replace function get_employees1(dep varchar2) return id_tab1 is
l_emp_list id_tab1; ---id_tab1 is a table of varchar2(CREATE OR REPLACE type id_tab1 as table of varchar2(10);)
str varchar2(300);
begin
str := 'select e.last_name from employees e join departments d on
e.department_id=d.department_id
where d.department_name= :dep';
execute immediate str bulk collect into l_emp_list using dep;
return l_emp_list;
end;

The Link Between Webform Combobox Data and the Database (SQL Server & ASP.NET)

The title, while long, pretty much says it all.
What I have is a master table with a bunch of supporting table relations through foreign keys. For a few of the foreign tables, upon attempting to insert a record into the master table where one of the foreign keys doesn't exist, the data would be passed to the foreign table to create the record first, thereby making the constraint valid and passing the key to the created record back to the insert procedure of the master table.
This data comes from a form in String form, but naturally the foreign key will be an int. The process would look something like this:
-- ASP.NET Web Form --
Requestor Name: _____________ (combobox)
Request: _____________ (dropdownlist)
Date: _____________ (datepicker)
This is a super simplified version, but assume we have a master table with the above data, where both names are foreign keys to a People table. The name fields are comboboxes with a populated list of names linking to People. However, if I wanted to enter a person who didn't yet exist in the People table, the procedure should first create the Person, then use the ID from that new record as the foreign key in the Master table containing columns for the above.
I'm using SQL Server and ASP.NET with VB.NET codebehind. I've been scratching my head over this one for awhile, how to pass data (in different forms such as a foreign key or string) between the web server and DB server, as well as where to validate / transform the data.
It seems the entered name will be passed as an ID if the foreign key exists, and a String if not.
This is my most perplexing problem so far, and no idea where else to look. I've read up on Scott Mitchell's site and others.
MY SOLUTION (?)
The best I can come up with is to pass the user input from the user as a string and convert it to int in the T-SQL procedure. If the value was selected from the drop down, it should match precisely with a valid foreign key. If it doesn't match, then create a new Person and return a foreign key. Is this best practice?
This seems complicated because it is. You have to get your hands dirty. If you need a relational database with ACID support, there's no auto-magical way of getting around it.
Relational databases 101: The primary key must exist before the foreign key can be populated (This is the reason why data warehouse developers populate the dimension table before the fact table). You'll have to design the logic to validate that the primary key exists, insert and get the key if not, and just get the key if exists.
Here's my implementation. I don't know if it's the best, but it worked well for me. Basically I take the values from the controls; in the case of the combobox I need the values from both the TextBox and DropDownList. I then pass those values to the following function in my codebehind:
'This method determines if the name selected already exists in the selection
' options and if so assigns the corresponding ID value to an object variable,
' if not it assigns the value of the `TextBox` to the variable.
Protected Function _ValidateValues(ByRef ddl As DropDownList, ByRef cb As TextBox) As Object
'Ensures the selected value is valid by checking against the entered value in the textbox
If Not String.IsNullOrEmpty(cb.Text) Then
If ddl.Items.Count > 0 Then
If StrComp(cb.Text, ddl.SelectedItem.ToString) = 0 Then
Return ddl.Items.Item(ddl.SelectedIndex).Value 'Returns the index of dropdown selected name
End If
End If
'This counts the capital letters in the entered value and if fewer than 2
' auto capitalizes the first letters. This also allows for project code
' names such as "DOORS" and people names such as "Allen McPherson" etc.
' Be careful though because if "allen McPherson" is entered, it will NOT
' be corrected, though it displays correctly.
Dim rg As New Regex("[A-Z]")
Dim mc As MatchCollection = rg.Matches(cb.Text)
If mc.Count < 2 Then
Return StrConv(cb.Text, VbStrConv.ProperCase)
Else : Return cb.Text
End If
End If
'Returns a SQL DB NULL object if an empty string is submitted
Return DBNull.Value
End Function
Then my stored procedure handles the values something like so...
(Forgive me if I neglected to replace some of the values. I tried to catch them all.)
CREATE PROCEDURE spInsertUser
#User nvarchar(50) = NULL,
#Role nvarchar(50) = NULL,
#RecordID int output -- Returned Value
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- CHECK IF USER EXISTS
-- Insert new record to Users table if the requested user doesn't exist
-- Needed to ensure that the foreign keys are relevant
IF #User = '' OR #User IS NULL BEGIN SET #User = NULL SET #RecordID = NULL END --Ensures that an empty string cannot be submitted, thereby causing an error.
ELSE BEGIN
declare #forename varchar(50), #surname varchar(50)
declare #uid table (ID int)
declare #users table (ID smallint, Name nvarchar(50))
insert into #users
select ID, Name from Users
--If the value can be converted into an int, we need go no further.
BEGIN TRY SET #RecordID = CONVERT(smallint, #User) END TRY
BEGIN CATCH
BEGIN TRY --Otherwise, attempt to parse the name
Set #User = LTRIM(RTRIM(#User)) --Trim the extra space at the beginning and end. This ensures the following "IF" test will evaluate properly.
IF NOT CHARINDEX(' ', #User) > LEN(#User) AND CHARINDEX(' ', #User) > 0 BEGIN -- Confirm First & Last Name exist
Set #forename = RTRIM(LEFT(#User, CHARINDEX(' ',#User,0)-1))
Set #surname = LTRIM(RIGHT(#User, LEN(#User) - CHARINDEX(' ',#User,0)))
Set #User = #forename + ' ' + #surname --Ensure that there is a valid First & Last name
IF LEN(#forename) > 1 AND LEN(#surname) > 1 BEGIN -- Confirm First & Last Name exist
--First ensure that the User doesn't already exist, and if
-- so use their ID, if not insert the new User.
IF NOT EXISTS (select Name from #users where Name like #User) BEGIN --Check if the user already exists
INSERT INTO Users (Name, Forename, Surname) OUTPUT INSERTED.ID INTO #uid Values (#User, -- If not, insert them
#forename, #surname) --Nicely manicured first, last, and full names
SET #RecordID = CONVERT(smallint, (select MAX(ID) from #uid)) END -- Now set the Role to the ID of the new user
ELSE BEGIN --Otherwise if the user already exists, set the Role to the ID of that user
SET #RecordID = (select ID from #users where Name like #User) END
IF NOT EXISTS (select * from rUsersInRoles where UserID = #RecordID) BEGIN
--Do some string manipulation to increase the chances of matching the role
SET #Role = REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(#Role)), ' ', '%'), '.', '%'), '#', '%') --Trims & replaces spaces & periods with wildcards
INSERT INTO rUsersInRoles (UserID, UserRoleID) VALUES
(#RecordID, (select top 1 ID from rUserRoles where Role like #Role)) END
END
END
END TRY
BEGIN CATCH END CATCH
END CATCH
END
END
This stored procedure deals with the case of User Roles as well. If the more simple case of Users only is needed, simply remove the clauses dealing with the checking and insertion of User Roles. :)

How to find name of the stored procedure using Column name in Oracle 11g

I have hundreds of stored procedures and i want to find out the name of the procedure which uses the particular column name in query
This will do it, but might produce false positives for generic column names
SELECT DISTINCT type, name
FROM dba_source
WHERE owner = 'OWNER'
AND text LIKE '%COLUMN_NAME%';
where OWNER is the schema which owns the stored procedures you want to search and COLUMN_NAME is the column name that you want to find. If you don't use mixed case column names then you can replace the last line with
AND UPPER(text) LIKE '%COLUMN_NAME%';
and enter the column name in capitals to get a case insensitive search.
There is no guaranteed way, but you can search user/all/dba_source using regexp_like to check for whole words, and cross-reference that with user/all/dba_dependencies to narrow down the list of packages to check.
select s.name, s.type, s.line, s.text
from user_source s
where ltrim(s.text,chr(9)||' ') not like '--%'
and regexp_like(lower(s.text),'\Wyour_column_name_here\W')
and (s.name, s.type) in
( select d.name, d.type
from user_dependencies d
where d.referenced_owner = user
and d.referenced_name = 'YOUR_TABLE_NAME_HERE' );
or if there could be references to it from other schemas,
select s.owner, s.name, s.type, s.line, s.text
from all_source s
where ltrim(s.text,chr(9)||' ') not like '--%'
and regexp_like(lower(s.text),'\Wyour_column_name_here\W')
and (s.owner, s.name, s.type) in
( select d.owner, d.name, d.type
from all_dependencies d
where d.referenced_owner = user
and d.referenced_name = 'YOUR_TABLE_NAME_HERE' );
You might make it just use select distinct s.owner, s.name, s.type ... to get a list of objects to investigate.

Resources