I am trying to write a stored procedure to concatenate multiple rows of text together to return it as a single string. For example:
CREATE TABLE TEST (
ID INTEGER,
SEQ INTEGER,
TEXT VARCHAR(255));
COMMIT;
INSERT INTO TEST (ID, SEQ, TEXT) VALUES (1, 1, "LINE 1");
INSERT INTO TEST (ID, SEQ, TEXT) VALUES (1, 2, "LINE 2");
INSERT INTO TEST (ID, SEQ, TEXT) VALUES (1, 3, "LINE 3");
COMMIT;
SET TERM !!;
CREATE PROCEDURE concat_names (iID INTEGER)
RETURNS (CONCAT VARCHAR(2000))
AS
DECLARE VARIABLE name VARCHAR(255);
BEGIN
CONCAT = '';
FOR SELECT TEXT FROM TEST where id=:iID INTO :name
DO BEGIN
CONCAT = CONCAT || name;
END
END!!
SET TERM ;!!
commit;
However when I run:
select concat from concat_names(1);
It always returns zero rows.
Any ideas?
You forget for SUSPEND. Your proc should look like this:
SET TERM !!;
CREATE PROCEDURE concat_names (iID INTEGER)
RETURNS (CONCAT VARCHAR(2000))
AS
DECLARE VARIABLE name VARCHAR(255);
BEGIN
CONCAT = '';
FOR SELECT TEXT FROM TEST where id=:iID INTO :name
DO BEGIN
CONCAT = CONCAT || name;
END
SUSPEND;
END!!
SET TERM ;!!
You can achieve the same result without stored proc. Use LIST aggregate function:
SELECT LIST(text, '') FROM TEST where id=:iID
Second parameter of LIST is a delimiter. If you call LIST with only field name, then comma ',' will be used to separate values.
In the case the field TEST can ben null and you don't want to set to null the whole result it is useful to use:
CONCAT = CONCAT || coalesce(name,'');
instead of
CONCAT = CONCAT || name;
Without utilizing a Stored Proc and using version Firebird 2.5, the LIST aggregation function will return "Comma-separated string concatenation of non-NULL values in the column"*. Using the aforementioned TEST table, the SQL
SELECT LIST(TEXT)
FROM TEST
returns
LINE 1,LINE 2,LINE 3
This may be of some interest.
*Taken from the Firebird reference page here
Related
I am a newbie in the area of redshift data modeling and got myself into trouble with an error.ERROR:
--Final version
syntax error ERROR: operator does not exist: text | record Hint: No
operator matches the given name and argument type(s). You may need to
add explicit type casts. Where: SQL statement "SELECT 'create temp
table ' || $1 || ' as select * from' | $2 |" PL/pgSQL function "egen"
line 36 at execute statement [ErrorId:
1-61dc32bf-0a451f5e2c2639235abb8876]
I am trying to do a simple transformation that gets returned in output when the procedure is called. (As of now I got to find from the documentation we have to use either temp table or cursors to achieve this)
Pseudocode:
I am trying to restrict data to its latest one in (2019) Get the
list of managers create columns if a person is a manager or not from the list.
Return it as a result
Data looks as follows Employee Data
My Select query works fine out of the procedure, please find my complete code below.
CREATE OR REPLACE PROCEDURE EGEN(tmp_name INOUT varchar(256) )
AS $$
DECLARE
--As i have less data managed to create it as an array or please use temp or table and join it with the actual query to perform transformation
MGR_RECORD RECORD;
DATAS RECORD;
item_cnt int := 0;
V_DATE_YEAR int := 0;
BEGIN
--EXECUTE (select cast(extract(year from current_date) as integer)-3) INTO V_DATE_YEAR;
--Manager Records are stored here below
SELECT DISTINCT managerid from "dev"."public"."emp_salary" INTO MGR_RECORD;
SELECT employeeid,
managerid,
promotion,
q_bonus,
d_salary,
case when contractor = 'x'
then 'TemporaryEmployee'
else 'PermanentEmployee'
END as EmployeeType,
-- IFstatement not supported under select query
case when employeeid in (select distinct managerid FROM "dev"."public"."emp_salary" )
then 'Manager'
else 'Ordinary FTE'
END as FTETYPE
FROM "dev"."public"."emp_salary" where cast(extract(year from promotion) as int ) >= 2019 into DATAS;
--COMMIT;
tmp_name := 'ManagerUpdatedTable';
EXECUTE 'drop table if exists ' || tmp_name;
EXECUTE 'create temp table ' || 'ManagerUpdatedTable' || ' as select * from' |DATAS| ;
END;
$$ LANGUAGE plpgsql;
-- Call tests CALL EGEN('myresult'); SELECT * from myresult;
Also, additional query (Can we replace )
case when employeeid in (select distinct managerid FROM "dev"."public"."emp_salary" )
then 'Manager'
else 'Ordinary FTE'
END as FTETYPE
this transform in query to IF , if possible please provide details.
Thanks and Regards,
Gabby
When I pass more than one id in sql server stored procedure it throws error like this==> Conversion failed when converting the varchar value '1,2' to data type int.
and this is the sql query
===>SELECT * FROM SomeTAble WHERE colName in(#Ids)
If your stored procedure parameter expecting varchar(n), please have a look at accepted answer from T-SQL split string to split the value from a varchar.
Then you can apply the function in your stored procedure, you can simply change the query to something like this:
alter procedure your_stored_procedure
#ids varchar(50)
as
begin
select *
from some_table
where colName in (splitstring(#ids))
end
go
However, if your stored procedure accepting int as parameter, please change it to varchar or any data type. Your stored procedure won't work because int will only accept single integer value.
You have to split string into rows first.
for do that you can use my sql Splitext function
Here is Installing Script
DROP FUNCTION IF EXISTS [dbo].[SplitText]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SplitText]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql #statement = N'CREATE FUNCTION [dbo].[SplitText]
( #TextForSplit varchar(1000)
, #SplitWith varchar(5) = '',''
)
RETURNS #DataSource TABLE
(
ID TINYINT identity,
[Value] VARCHAR(500) NOT NULL
)
AS
BEGIN
DECLARE #XML xml = N''<r><![CDATA['' + REPLACE(#TextForSplit, #SplitWith, '']]></r><r><![CDATA['') + '']]></r>''
INSERT INTO #DataSource ([Value])
SELECT RTRIM(LTRIM(T.c.value(''.'', ''NVARCHAR(128)'')))
FROM #xml.nodes(''//r'') T(c)
DELETE #DataSource WHERE [VALUE] = ''''
RETURN
END
END
GO
And this is how to use it.
SELECT * FROM SomeTAble WHERE colName in( select value from Splittext('1,2,3,4,5' , ','))
I have a DB2 stored procedures to get n number of sequence values and then combine them into a single comma delimited string and return it. The concat function in the stored procedure is not working as expected.
CREATE PROCEDURE REFWTX.GET_SEQ_VALUES (in numb integer, OUT SEQVALUES VARCHAR(10000))
LANGUAGE SQL
SPECIFIC GET_SEQ_VALUES
BEGIN
DECLARE SEQ_VAL Integer;
DECLARE CUR_COUNT INTEGER;
SET CUR_COUNT=1;
WHILE (CUR_COUNT <= numb) DO
SELECT NEXTVAL FOR REFWTX.ACK_999_INTR_CTRL_NO_SEQ INTO SEQ_VAL FROM SYSIBM.SYSDUMMY1;
set SEQVALUES = SEQVALUES|| ',' || CHAR(SEQ_VAL);
SET CUR_COUNT=CUR_COUNT+1;
END WHILE;
return;
END
The portion of the procedure:
set SEQVALUES = SEQVALUES|| ',' || CHAR(SEQ_VAL);
is not working as expected. How do I concatenate strings in stored procedures?
You haven't told us how it is "not working as expected". Example inputs and output would be useful.
My guess would be that since you never initialize SEQVALUES, it is set to NULL and concatenating anything with NULL gives you NULL.
Also, instead of
SELECT NEXTVAL FOR REFWTX.ACK_999_INTR_CTRL_NO_SEQ INTO SEQ_VAL FROM SYSIBM.SYSDUMMY1;
why not use
VALUES NEXTVAL FOR REFWTX.ACK_999_INTR_CTRL_NO_SEQ INTO SEQ_VAL;
I have a need to run a recursive CTE within a stored proc, but I can't get it past this:
SQL0104N An unexpected token "with" was found following "SET count=count+1;
". Expected tokens may include: "". LINE NUMBER=26.
My google-fu showed a couple of similar topics, but none with resolution.
The query functions as expected outside of the stored proc, so I'm hoping that there's some syntactic sugar I'm missing that'll let this work. Similarly, the proc compiles and works without the query.
Here's a contrived example:
--setup
create table tree (id integer, name varchar(50), parent_id integer);
insert into tree values (1, 'Alice', null);
insert into tree values (2, 'Bob', 1);
insert into tree values (3, 'Charlie', 2);
-
- the proc
create or replace procedure testme() RESULT SETS 1 LANGUAGE SQL
BEGIN
DECLARE SQLSTATE CHAR(5);
DECLARE SQLCODE integer default 0;
DECLARE count INTEGER;
DECLARE sum INTEGER;
DECLARE total INTEGER;
DECLARE id INTEGER;
DECLARE curs CURSOR WITH RETURN FOR
select count,sum from sysibm.sysdummy1;
DECLARE hiercurs CURSOR FOR
select id from tree order by id;
SET bomQuery='';
PREPARE stmt FROM bomQuery;
SET count = 0;
SET sum = 0;
set total = 0;
OPEN hiercurs;
FETCH hiercurs INTO id;
WHILE (SQLCODE <> 100) DO
SET count=count+1;
with org (level,id,name,parent_id) as
(select 1 as level,root.id,root.name,root.parent_id from tree root where root.id=id
union all
select level+1,employee.id,employee.name,employee.parent_ id from org boss, tree employee
where level < 5 and employee.parent_id=boss.id)
select count(1) into sum from org;
SET total=total+sum;
FETCH hiercurs INTO id;
END WHILE;
CLOSE hiercurs;
OPEN curs;
END
the cte in db2 doesn't seem to recognize the scalar result of the query, and so it won't let the select into work (not a problem on Oracle or SQLServer)...solution is to open a cursor and FETCH INTO (instead of SELECT INTO) instead.
In addition to rjb's suggestion of enclosing the CTE query inside a cursor, you can also stuff the CTE into a user-defined function or a view, and then code a straight select against that object into your stored procedure.
i'm creating a procedure to update/insert a table using merge statement(upsert).now i have a problem: using procedure parameters i have to do this upsert.
procedure xyz( a in table.a%type,b in table.b%type,....)
is
some local variables;
begin
merge into target_table
using source_table --instead of the source table, i have to use procedure parameters here
on (condition on primary key in the table)
when matched then
update the table
when not matched then
insert the table ;
end xyz;
so how to use procedure parameters instead of source table in merge statement?? or
suggest me a query to fetch the procedure parameters and use it as source table values.
help me please.
Thanks in advance.
I know that I'm eight years late to the party, but I think that I was trying to do something similar to what you were doing, but trying to Upsert based on parameters passed into a stored procedure that returns an empty string on success and an error on failure back to my VB Code. Below is all of my code along with comments explaining what I did, and why I did it. Let me know if this helps you or anyone else. This is my first time answering a post.
PROCEDURE UpsertTSJobData(ActivitySeq_in IN NUMBER,
Owner_in In VARCHAR2,
NumTrailers_in IN NUMBER,
ReleaseFormReceived_in IN NUMBER,
Response_out OUT VARCHAR2) AS
err_num NUMBER;
err_msg VARCHAR2(4000);
BEGIN
--This top line essentially does a "SELECT *" from the named table
--and looks for a match based on the "ON" statement below
MERGE INTO glob1app.GFS_TS_JOBDATA_TAB tsj
--This select statement is used for the INSERT when no match
--is found and the UPDATE when a match is found.
--It creates a "pseudo-table"
USING (
SELECT ActivitySeq_in AS ActSeq,
Owner_in As Owner,
NumTrailers_in As NumTrailers,
ReleaseFormReceived_in As ReleaseFormReceived
FROM DUAL) input
--This ON statement is what we're doing the match on to find
--matching records. This decides whether it will be an
--INSERT or an UPDATE
ON (tsj.Activity_seq = ActivitySeq_in)
WHEN MATCHED THEN
--Here we UPDATE based on the passed in input table
UPDATE
SET OWNER = input.owner,
NUMTRAILERS = input.NumTrailers,
RELEASEFORMRECEIVED = input.releaseformreceived
WHEN NOT MATCHED THEN
--Here we INSERT based on the passed in input table
INSERT (
ACTIVITY_SEQ,
OWNER,
NUMTRAILERS,
RELEASEFORMRECEIVED
)
VALUES (
input.actseq,
input.owner,
input.numtrailers,
input.releaseformreceived
);
Response_out := '';
EXCEPTION
WHEN OTHERS THEN
err_num := SQLCODE;
err_msg := SUBSTR(SQLERRM, 1, 3900);
Response_out := TO_CHAR (err_num) || ': ' || err_msg;
END;
Maby something like
DECLARE V_EXISTS NUMBER;
BEGIN SELECT COUNT(*) INTO V_EXISTS FROM TARGET_TABLE WHERE PK_ID = :ID;
IF V_EXISTS > 0 THEN
-- UPDATE
ELSE
-- INSERT
END IF;
END;
Also, you may try to use so-called tempotary table (select from DUAL)
CREATE TABLE TEST (N NUMBER(2), NAME VARCHAR2(20), ADRESS VARCHAR2(100));
INSERT INTO TEST VALUES(1, 'Name1', 'Adress1');
INSERT INTO TEST VALUES(2, 'Name2', 'Adress2');
INSERT INTO TEST VALUES(3, 'Name3', 'Adress3');
SELECT * FROM TEST;
-- test update
MERGE INTO TEST trg
USING (SELECT 1 AS N, 'NameUpdated' AS NAME,
'AdressUpdated' AS ADRESS FROM Dual ) src
ON ( src.N = trg.N )
WHEN MATCHED THEN
UPDATE
SET trg.NAME = src.NAME,
trg.ADRESS = src.ADRESS
WHEN NOT MATCHED THEN
INSERT VALUES (src.N, src.NAME, src.ADRESS);
SELECT * FROM TEST;
-- test insert
MERGE INTO TEST trg
USING (SELECT 34 AS N, 'NameInserted' AS NAME,
'AdressInserted' AS ADRESS FROM Dual ) src
ON ( src.N = trg.N )
WHEN MATCHED THEN
UPDATE
SET trg.NAME = src.NAME,
trg.ADRESS = src.ADRESS
WHEN NOT MATCHED THEN
INSERT VALUES (src.N, src.NAME, src.ADRESS);
SELECT * FROM TEST;
DROP TABLE TEST;
see here
Its very difficult to tell from you question exactly what you what, but I gather you want the table that you are merging into ( or on ) to be dynamic. In that case, what you should be using is the DBMS_SQL package to create dynamic SQL