How to create a Sybase stored procedure - stored-procedures

I'm new to Sybase and i need to create a stored procedure to gather space, basically convert these into a procedure:
create proc sp_maint
#dbname varchar(30), #segname varchar(30),
#devname varchar(30), #devsize int,
#freesize int, #free_percentage int
as declare #sizeinpg float,

create proc sp_maint
#dbname varchar(30),
#segname varchar(30),
#devname varchar(30),
#devsize int,
#freesize int,
#free_percentage int
as
declare #sizeinpg float,
#perc float,
#segbit int,
#seg int,
#pagefl float
BEGIN
/* for all segments */
select #seg = segment
from syssegments
where name = #segname
select DATE=convert(char(8),getdate(),1),
DB_NAME=db,
SEGMENT_NAME=seg,
Allocated_Space=convert(int,(round(size,0))),
Free_Space=convert(int,round(MBfree,0)),
Free_Percent=convert(int,(round(((MBfree/size)*100),1))),
/* get rid of blanks */
select #dbname = ltrim(rtrim(#dbname))
select #segname = ltrim(rtrim(#segname))
**strong text**

Related

stored procedure for inserting values of tables into another tables with automatic identifier as FK PGadmin4

I want to make an insert procedure for specific values of an table into another existing table.
The dificulty is that my excisting table has automatic identifiers as fk of another table.
When I insert them individually, I use a look up function. But now I don't known in PGadmin how to put this in a procedure. In oarcle I can use collections but in pgadmin I can't figure it out.
my tables:
CREATE TABLE public.field (field_id INT GENERATED BY DEFAULT AS IDENTITY
CONSTRAINT pk_veld_id PRIMARY KEY,
object_number INT,
experiment_number INT,
repetition INT,
plants_field INT,
stem_field INT,
plants_square_meter numeric,
stem_square_meter_start numeric,
stem_square_meter_end numeric,
date_extra_stem date,
row_number_field INT);
CREATE TABLE public.sticky_plates_fields (ID_sticky_plate INT GENERATED BY DEFAULT AS IDENTITY
CONSTRAINT pk_sticky_plate_id PRIMARY KEY,
sticky_plate_number INT,
brand_sticky_plate varchar,
version_plate numeric,
field_id INT constraint fk_sticky_plates_fields references field );
ALTER TABLE IF EXISTS public.sticky_plates_fields
ADD CONSTRAINT sticky_plates_fields_unique UNIQUE (sticky_plate_number, field_id);
DROP TABLE IF EXISTS public.make_sticky_plate_counts CASCADE;
CREATE TABLE public.make_sticky_plate_counts (
experiment_number INT,
object_number INT,
repetition INT,
sticky_plate_number INT,
brand_sticky_plate varchar,
version_plate numeric,
date_start date,
date_count date,
species varchar,
stage varchar,
count_species INT);
look_up _function:
CREATE OR REPLACE FUNCTION project.lookup_field_id
(p_objectnumber INT,
p_experimentnumber INT,
p_repetition INT)
RETURNS integer
LANGUAGE 'plpgsql'
AS
$BODY$
DECLARE
ln_field_id integer;
BEGIN
SELECT field_id INTO ln_field_id
FROM field
WHERE p_objectnumber = object_number AND p_experimentnumber = experiment_number AND p_repetition = repetition;
RETURN ln_field_id;
END;
$BODY$;
values:
insert into public.field(object_number,experiment_number,repetition,stem_field,stem_square_meter_start,stem_square_meter_end,date_extra_stem,row_number_field)
values (1,4072022,1,20,2.5,3.3,TO_DATE('1-04-2022','DD-MM-YYYY'),10);
insert into public.field(object_number,experiment_number,repetition,stem_field,stem_square_meter_start,stem_square_meter_end,date_extra_stem,row_number_field)
values (1,4072022,2,20,2.5,3.3,TO_DATE('1-04-2022','DD-MM-YYYY'),15);
insert into public.field(object_number,experiment_number,repetition,stem_field,stem_square_meter_start,stem_square_meter_end,date_extra_stem,row_number_field)
values (1,4072022,3,20,2.5,3.3,TO_DATE('1-04-2022','DD-MM-YYYY'),20);
insert into public.field(object_number,experiment_number,repetition,stem_field,stem_square_meter_start,stem_square_meter_end,date_extra_stem,row_number_field)
values (1,4072022,4,20,2.5,3.3,TO_DATE('1-04-2022','DD-MM-YYYY'),25);
insert into public.field(object_number,experiment_number,repetition,stem_field,stem_square_meter_start,stem_square_meter_end,date_extra_stem,row_number_field)
values (2,4072022,1,20,2.5,3.3,TO_DATE('1-04-2022','DD-MM-YYYY'),10);
insert into public.field(object_number,experiment_number,repetition,stem_field,stem_square_meter_start,stem_square_meter_end,date_extra_stem,row_number_field)
values (2,4072022,2,20,2.5,3.3,TO_DATE('1-04-2022','DD-MM-YYYY'),15);
insert into public.field(object_number,experiment_number,repetition,stem_field,stem_square_meter_start,stem_square_meter_end,date_extra_stem,row_number_field)
values (2,4072022,3,20,2.5,3.3,TO_DATE('1-04-2022','DD-MM-YYYY'),20);
insert into public.sticky_plates_fields(sticky_plate_number,brand_sticky_plate,version_plate,field_id)
values(2,'BIOBEST',3,project.lookup_field_id(1,4072022,2));
insert into public.sticky_plates_fields(sticky_plate_number,brand_sticky_plate,version_plate,field_id)
values(1,'BIOBEST',3,project.lookup_field_id(1,4072022,1));
insert into public.sticky_plates_fields(sticky_plate_number,brand_sticky_plate,version_plate,field_id)
values(3,'BIOBEST',3,project.lookup_field_id(1,4072022,3));
insert into public.sticky_plates_fields(sticky_plate_number,brand_sticky_plate,version_plate,field_id)
values(4,'BIOBEST',3,project.lookup_field_id(1,4072022,4));
insert into public.make_sticky_plate_counts(experiment_number,object_number,repetition,sticky_plate_number,brand_sticky_plate,version_plate,date_start,date_count,species,stage,count_species)
values(4072022,2,1,6,'BIOBEST',2.1,TO_DATE('1-04-2022','DD-MM-YYYY'),TO_DATE('14-04-2022','DD-MM-YYYY'),'WHITE_FLY_T','ADULT',12) ;
insert into public.make_sticky_plate_counts(experiment_number,object_number,repetition,sticky_plate_number,brand_sticky_plate,version_plate,date_start,date_count,species,stage,count_species)
values(4072022,2,2,7,'BIOBEST',2.1,TO_DATE('1-04-2022','DD-MM-YYYY'),TO_DATE('14-04-2022','DD-MM-YYYY'),'WHITE_FLY_T','ADULT',12) ;
insert into public.make_sticky_plate_counts(experiment_number,object_number,repetition,sticky_plate_number,brand_sticky_plate,version_plate,date_start,date_count,species,stage,count_species)
values(4072022,2,3,8,'BIOBEST',2.1,TO_DATE('1-04-2022','DD-MM-YYYY'),TO_DATE('14-04-2022','DD-MM-YYYY'),'WHITE_FLY_T','ADULT',12) ;
insert into public.make_sticky_plate_counts(experiment_number,object_number,repetition,sticky_plate_number,brand_sticky_plate,version_plate,date_start,date_count,species,stage,count_species)
values(4072022,2,4,9,'BIOBEST',2.1,TO_DATE('1-04-2022','DD-MM-YYYY'),TO_DATE('14-04-2022','DD-MM-YYYY'),'WHITE_FLY_T','ADULT',12) ;
try out of stored procedure
Here I want some values of table make_sticky_plate_counts to insert into table sticky_plates_fields.
I don't know how I can make a procedure to insert the whole (distinct table) winto the sticky plate field table and using the look up function for finding the related FK integer.
CREATE OR REPLACE PROCEDURE insert_records
() LANGUAGE 'plpgsql'
AS
$BODY$
DECLARE
p_object_number INT;
p_experiment_number INT;
p_r_epetitition INT;
p_sticky_plate_number INT;
p_brand_sticky_plate VARCHAR;
p_version_plate VARCHAR;
max_rownumbers_insert INT := 0;
BEGIN
max_rownumbers_insert := SELECT COUNT(*) FROM (SELECT DISTINCT object_number,experiment_number,repetition FROM make_sticky_plate_counts) as temp;
FOR i IN 1..max_rownumbers_insert
LOOP
p_object_number := SELECT object_number [i] FROM (SELECT DISTINCT object_number,experiment_number,repetition FROM make_sticky_plate_counts) as temp ;
p_experiment_number := SELECT experiment_number [i] FROM (SELECT DISTINCT object_number,experiment_number,repetition FROM make_sticky_plate_counts) as temp ;
p_repetitition:= SELECT repetitition [i] FROM (SELECT DISTINCT object_number,experiment_number,repetition FROM make_sticky_plate_counts) as temp ;
p_sticky_plate_number:=SELECT sticky_plate_number [i] FROM (SELECT DISTINCT object_number,experiment_number,repetition FROM make_sticky_plate_counts) as temp);
p_brand_sticky_plate :=SELECT brand_sticky_plate [i] FROM (SELECT DISTINCT object_number,experiment_number,repetition FROM make_sticky_plate_counts) as temp);
p_version_plate :=SELECT version_plate [i] FROM (SELECT DISTINCT object_number,experiment_number,repetition FROM make_sticky_plate_counts) as temp);
INSERT INTO sticky_plate_fields(field_id, sticky_plate_number, brand_sticky_plate,version_plate)
VALUES (project.lookup_field_id(p_object_number,p_experiment_number,p_repetition),p_sticky_plate_number,p_brand_sticky_plate,p_version_plate);
END LOOP; ```
I could figure it out. Maybe it is helpfull for someone else:
CREATE OR REPLACE PROCEDURE insert_records
() LANGUAGE 'plpgsql'
AS
$BODY$
DECLARE
curs cursor for select * FROM (SELECT DISTINCT object_number,experiment_number,repetition,sticky_plate_number,brand_sticky_plate,version_plate FROM make_sticky_plate_counts) as temp;
BEGIN
FOR row IN curs LOOP
INSERT INTO sticky_plates_fields(field_id, sticky_plate_number, brand_sticky_plate,version_plate)
VALUES (project.lookup_field_id(row.object_number,row.experiment_number,row.repetition),row.sticky_plate_number,row.brand_sticky_plate,row.version_plate);
END LOOP;
END ;
$BODY$;

Siddhi QL : In-Memory table outer join with Input Stream

I want to calculate % of protocols appearing in a network traffic in continuous way such that these % keeps on being updated with new events. A pie chart is generated and updated with the percentages. Since I need both new and previous data for the calculation, I decided to use in-memory table to keep events for a longer time (say a day).
As event tables are usable only when joined with event streams, I chose outer join to get old values as well. Being interested in just protocols and their percentages, I need just two columns but I am unable to apply aggregate function in outer join. The query I have so far generated is:
#Import('MAINInStream:1.0.0')
define stream MAINInStream (ts string, uid string, id_orig_h string, id_orig_p int, id_resp_h string, id_resp_p int, proto string, service string, duration double, orig_bytes long, resp_bytes long, conn_state string, local_orig bool, local_resp bool, missed_bytes long, history string, orig_pkts long, orig_ip_bytes long, resp_pkts long, resp_ip_bytes long, tunnel_parents string, sensorname string);
#Export('ProtocolStream:1.0.0')
define stream ProtocolStream (protocol string, count int);
define table mem_conn_table (timestamp long, id_orig_h string, id_orig_p int, id_resp_h string, id_resp_p int, proto string);
from MAINInStream
select time:timestampInMilliseconds(time:dateAdd(str:replaceAll(ts,'T',' '), 5, 'hour',"yyyy-MM-dd HH:mm:ss"),'yyyy-MM-dd HH:mm') as timestamp, id_orig_h, id_orig_p, id_resp_h, id_resp_p, proto
insert into intermediateStream;
from MAINInStream
select time:timestampInMilliseconds(time:dateAdd(str:replaceAll(ts,'T',' '), 5, 'hour',"yyyy-MM-dd HH:mm:ss"),'yyyy-MM-dd HH:mm') as timestamp, id_orig_h, id_orig_p, id_resp_h, id_resp_p, proto
group by id_resp_p
insert into mem_conn_table;
from intermediateStream#window.externalTimeBatch(timestamp,1min, timestamp, 1min) as i right outer join mem_conn_table[time:dateDiff(time:currentTimestamp(),cast(timestamp,"string"), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss") == 0] as mc
on i.timestamp == mc.timestamp
SELECT (ifThenElse(mc.id_resp_p == 21,'FTP', ifThenElse(mc.id_resp_p == 22,'SSH', ifThenElse(mc.id_resp_p == 25,'SMTP', ifThenElse(mc.id_resp_p == 445,'SMB','MYSQL'))))) as protocol , cast(count(mc.id_resp_p),'int') as count
insert into ProtocolStream;
I am batching window with one external minute and then getting protocols and their counts, but it isn't giving me any output.
Any suggestions?
You cannot use outer joins with in-memory tables. If you need, you can emit events resides in in-memory table to a intermediate stream and use it for joining (guide). However, for you scenario you can use externalTime window, instead of going with event tables. Try something similar to below;
#Import('MAINInStream:1.0.0')
define stream MAINInStream (ts string, uid string, id_orig_h string, id_orig_p int, id_resp_h string, id_resp_p int, proto string, service string, duration double, orig_bytes long, resp_bytes long, conn_state string, local_orig bool, local_resp bool, missed_bytes long, history string, orig_pkts long, orig_ip_bytes long, resp_pkts long, resp_ip_bytes long, tunnel_parents string, sensorname string);
#Export('ProtocolStream:1.0.0')
define stream ProtocolStream (protocol string, count long);
#Export('PercentageStream:1.0.0')
define stream PercentageStream (protocol string, count long, percentage double);
from MAINInStream
select
time:timestampInMilliseconds(time:dateAdd(str:replaceAll(ts,'T',' '), 5, 'hour',"yyyy-MM-dd HH:mm:ss"),'yyyy-MM-dd HH:mm') as timestamp,
(ifThenElse(mc.id_resp_p == 21,'FTP', ifThenElse(mc.id_resp_p == 22,'SSH', ifThenElse(mc.id_resp_p == 25,'SMTP', ifThenElse(mc.id_resp_p == 445,'SMB','MYSQL'))))) as protocol
id_orig_h, id_orig_p, id_resp_h, id_resp_p, proto
insert into intermediateStream;
from intermediateStream#window.externalTime(timestamp, 1 day)
select timestamp, count() as totalCount
insert into totalCountStream;
from intermediateStream#window.externalTime(timestamp, 1 day)
select timestamp, protocol, count() as count
group by protocol
insert into perProtocolCountStream;
from perProtocolCountStream
select protocol, count
insert into ProtocolStream;
from totalCountStream#window.time(1 min) as tcs join perProtocolCountStream#window.time(1 min) as pcs
select pcs.protocol, pcs.count as count, ((pcs.count/tcs.totalCount)) * 100 as percentage
on tcs.timestamp == pcs.timestamp
insert into PercentageStream;

While loop in IBM DB2 stored procedure endup in infinite looping

I am new with procedure. Somewhat I am getting the results too. But I got problem with a dynamic query. Stored query in a variable and tried to execute using cursor. But the loop only select the first result and execute infinitely. I couldn't find the error. How can I clear the error? Any help would be appreciated.
My Procedure is
CREATE PROCEDURE SPTEST1(IN tr_code INT, IN pen_type INT, IN pen_code INT, IN due_code INT, IN ord_dt DATE, IN finyr_cd INT, IN user_id varchar(50), IN server_ip varchar(100), OUT res INTEGER)
SPECIFIC sptest1
LANGUAGE SQL
P1:BEGIN
DECLARE trcd INTEGER;
DECLARE pentyp INTEGER;
DECLARE pencd INTEGER;
DECLARE duecd INTEGER;
DECLARE orddt DATE;
DECLARE finyrcd INTEGER;
DECLARE userid VARCHAR(50);
DECLARE serverip VARCHAR(100);
DECLARE ls_pentype CHAR(1);
DECLARE ls_voted CHAR(1);
DECLARE li_crmonth INTEGER;
DECLARE li_cryear INTEGER;
DECLARE ls_adhoc CHAR(1);
DECLARE ld_elgdt DATE;
DECLARE li_duecode INTEGER;
DECLARE li_headid INTEGER;
DECLARE tr_whr varchar(500);
DECLARE code_whr varchar(500);
DECLARE sqlstmt varchar(1000);
DECLARE EOF int DEFAULT 0;
DECLARE v_duplicate INT DEFAULT 0;--
DECLARE c_duplicate CONDITION FOR SQLSTATE '23505';
DECLARE STMT VARCHAR(120);
DECLARE SQLCODE INTEGER DEFAULT 0;
DECLARE SQLSTATE CHAR(5) DEFAULT '00000';
SET trcd = tr_code;
SET pentyp = pen_type;
SET pencd = pen_code;
SET duecd = due_code;
SET orddt = ord_dt;
SET finyrcd = finyr_cd;
SET userid = user_id;
SET serverip = server_ip;
SET ls_voted = 'V';
IF duecd > 50 THEN
SET ls_voted = 'C';
END IF;
FOR v_row AS <select query>
DO
SET ls_pentype = v_row.fmly_serv_oth_pen;
END FOR;
FOR date_month AS <select query>
DO
SET li_crmonth = date_month.credit_month;
SET li_cryear = date_month.credit_year;
END FOR;
FOR adhoc_row AS <select query>
DO
SET ls_adhoc = adhoc_row.is_adhoc_due;
END FOR;
FOR elgdt_row AS <select query>
DO
SET ld_elgdt = elgdt_row.eligible_uptodt;
END FOR;
FOR head_row AS <select query>
DO
SET li_headid = head_row.head_id;
SET li_duecode = duecd;
END FOR;
--portion for delete. have to enter
P2:BEGIN
DECLARE TRPOC CURSOR FOR <select query>
OPEN TRPOC;
FETCH FROM TRPOC INTO trcd;
WHILE(SQLSTATE = '00000') DO
insert into bg_run_test values(char(trcd));
END WHILE;
CLOSE TRPOC;
END P2;
END P1#
Here the while loop at the last executing infinitely. Where I try to insert in a table. Actually the result have only 200 rows.But inserting lacks.
I think you need an additional FETCH at the end of the WHILE loop after the INSERT statement, for it to successfully break out.
See this link which explains exactly this scenario.

How to read output value from stored procedure in c#?

Here is my stored procedure:
ALTER PROCEDURE sp_searchupdate
(
#id int,
#id_student int,
#output varchar(50) output,
#Tamil Varchar (100),
#English varchar (50),
#Maths Varchar (50),
#Science Varchar (50),
#SocialScience Varchar (50)
)
AS
IF EXISTS (SELECT * FROM studentresult WHERE id=#id)
BEGIN
UPDATE studentresult SET Tamil = #Tamil,English = #English, Maths = #Maths,Science = #Science,SocialScience = #SocialScience WHERE id = #id
SET #output='Updated'
RETURN
END
Else
BEGIN
IF EXISTS (SELECT * FROM student WHERE id=#id_student)
SET #output='EXIST'
RETURN
BEGIN
INSERT into studentresult (id_student,Tamil,English,Maths,Science,SocialScience) values (#id_student,#Tamil,#English,#Maths,#Science,#SocialScience)
SET #output='Inserted'
RETURN
END
END
If inserted data in front-end it need to shows 'inserted' or update means 'updated' or else 'exist'.
But for the above query didn't show notification message.
May i know, what my mistake in my code?
Can anyone guide me, I'M new stored procedure and .net.
Thanks,
It's rather unclear exactly what you are trying to achieve - why would you only insert into the studentresult record if the student record did NOT exist? Anyway, currently if no studentresult record exists then the procedure will always return after the check for the student record. There is no BEGIN...END after the IF EXISTS so only the first statement after the IF will be dependent on the result. Try:
ALTER PROCEDURE sp_searchupdate
(
#id int,
#id_student int,
#output varchar(50) output,
#Tamil Varchar (100),
#English varchar (50),
#Maths Varchar (50),
#Science Varchar (50),
#SocialScience Varchar (50)
)
AS
BEGIN
IF EXISTS (SELECT * FROM studentresult WHERE id=#id)
BEGIN
UPDATE studentresult SET Tamil = #Tamil,English = #English, Maths = #Maths,Science = #Science,SocialScience = #SocialScience WHERE id = #id
SET #output='Updated'
END
Else
BEGIN
IF EXISTS (SELECT * FROM student WHERE id=#id_student)
BEGIN
SET #output='EXIST'
END
ELSE
BEGIN
INSERT into studentresult (id_student,Tamil,English,Maths,Science,SocialScience) values (#id_student,#Tamil,#English,#Maths,#Science,#SocialScience)
SET #output='Inserted'
END
END
RETURN
END

call a stored procedure with more than one result sets into another procedure and work with them

I have a stored procedure that have 2 result sets and I want to call this sp into another stored procedure and get both it’s result sets and work with them. I have searched in Internet and Knew about the new fearture in sql server 2012 for this purpose. It is ‘RESULT SETS’.
Except using ‘Result sets’, is there another solution for call storedprocedure with more than one resultset into another procedure and work with them?
Pinal Dave has an example for using ‘Result Sets’
USE AdventureWorks2008R2
GO
CREATE PROCEDURE mySP1 (#ShiftID INT, #JobCandidateID INT)
AS
-- ResultSet 1
SELECT [ShiftID],[Name],[StartTime],[EndTime],[ModifiedDate]
FROM [HumanResources].[Shift]
WHERE [ShiftID] = #ShiftID
-- ResultSet 2
SELECT [JobCandidateID],[BusinessEntityID],[ModifiedDate]
FROM [HumanResources].[JobCandidate]
WHERE JobCandidateID = #JobCandidateID
CREATE PROCEDURE mySP2
AS
EXEC mySP1 #ShiftID = 2, #JobCandidateID = 5
WITH RESULT SETS
( ( [ShiftID] TINYINT,[Name] NVARCHAR(50),[StartTime] DATETIME, [EndTime] DATETIME,[UpdateDate] DATETIME -- Notice Name Change
),([JobCandidateID] INT,[BusinessEntityID] INT,[ModifiedDate] DATETIME ));
When we use the Result Set, we have the mysp1 results into these:
For ResultSet1:
[ShiftID] TINYINT,[Name] NVARCHAR(50),[StartTime] DATETIME,
[EndTime] DATETIME,[UpdateDate] DATETIME
And for Resultset2:
[JobCandidateID] INT,[BusinessEntityID] INT,[ModifiedDate] DATETIME
But now I want to query on these results in mySp2. How can I do this.
How can I select the values from :
[ShiftID] TINYINT,[Name] NVARCHAR(50),[StartTime] DATETIME
,[EndTime] DATETIME,[UpdateDate] DATETIME
And
[JobCandidateID] INT,[BusinessEntityID] INT,[ModifiedDate] DATETIME
The best solution may be using output variables in mySP1
CREATE PROCEDURE mySP1 (
#ShiftID INT
, #JobCandidateID INT
, #CUR1 CURSOR VARYING OUTPUT
)
SET NOCOUNT ON;
SET #CUR1 = CURSOR
FORWARD_ONLY STATIC FOR
SELECT [ShiftID],[Name],[StartTime],[EndTime],[ModifiedDate]
FROM [HumanResources].[Shift]
WHERE [ShiftID] = #ShiftID
OPEN #CUR1;
GO
to calling this sp:
DECLARE #MyCursor CURSOR;
EXEC dbo.mySP1 #ShiftID = 1, #JobCandidateID = 1, #CUR1 = #MyCursor OUTPUT;
WHILE (##FETCH_STATUS = 0)
BEGIN;
FETCH NEXT FROM #MyCursor;
END;
CLOSE #MyCursor;
DEALLOCATE #MyCursor;
Use a combination of this with a standar output or just declare another cursor output.

Resources