DB2 select statement does not return any rows - select

I wrote query:
select * from tbl1 as tbl1
where tbl1.pkey >= cast(080138738 as varchar(10))
and tbl1.pkey <= cast(080138738 as var char(10);
tbl1 contains row that its pkey value is 08013878 but this query dosn't retutn any rows.

Ok, let's start guessing, if you don't want to provide some fully reproducible example.
select *
from
(
VALUES
-- doesn't return a row
'080138738'
-- returns a row
--'80138738'
) tbl1 (pkey)
where tbl1.pkey >= CAST (080138738 as varchar(10))
and tbl1.pkey <= CAST (080138738 as varchar(10))
If you have pkey of VARCHAR data type then look at the example above.
Let's look at the result of the CAST (080138738 as varchar(10)) expression.
The integer 080138738 value is equal to the 80138738 one without leading zero(es), and namely this value is converted to the '80138738' VARCHAR value.
But the following query returns no rows obviously:
SELECT 1
FROM SYSIBM.SYSDUMMY1
WHERE '080138738' >=
'80138738' -- the result of CAST (080138738 as varchar(10))
AND '080138738' <=
'80138738' -- the result of CAST (080138738 as varchar(10))
The solution is to use correct data type for parameters.
--# SET TERMINATOR #
CREATE TABLE TBL1 (PKEY VARCHAR (10))#
INSERT INTO TBL1 (PKEY) VALUES '080138738'#
BEGIN
DECLARE V_STMT VARCHAR (500);
DECLARE V_CNT INT;
DECLARE C1 CURSOR FOR S1;
SET V_STMT =
'SELECT COUNT (*) FROM TBL1 '
|| 'WHERE pkey >= cast(? as varchar(10)) and pkey <= cast(? as varchar(10))';
PREPARE S1 FROM V_STMT;
-- Correct - using VARCHAR constants
OPEN C1 USING '080138738', '080138738';
-- Wrong - using INT constants
-- OPEN C1 USING 080138738, 080138738;
FETCH C1 INTO V_CNT;
-- We throw an exception, if the result is unexpected
IF V_CNT <> 1 THEN
SIGNAL SQLSTATE '75000' SET MESSAGE_TEXT = 'Not expected result';
END IF;
END
#
dbfiddle link

Related

PgSQL function returning table and extra data computed in process

In PgSQL I make huge select, and then I want count it's size and apply some extra filters.
execute it twice sound dumm,
so I wrapped it in function
and then "cache" it and return union of filtered table and extra row at the end where in "id" column store size
with q as (select * from myFunc())
select * from q
where q.distance < 400
union all
select count(*) as id, null,null,null
from q
but it also doesn't look like proper solution...
and so the question: is in pg something like "generator function" or any other stuff that can properly solve this ?
postgreSQL 13
myFunc aka "selectItemsByRootTag"
CREATE OR REPLACE FUNCTION selectItemsByRootTag(
in tag_name VARCHAR(50)
)
RETURNS table(
id BIGINT,
name VARCHAR(50),
description TEXT,
/*info JSON,*/
distance INTEGER
)
AS $$
BEGIN
RETURN QUERY(
WITH RECURSIVE prod AS (
SELECT
tags.name, tags.id, tags.parent_tags
FROM
tags
WHERE tags.name = (tags_name)
UNION
SELECT c.name, c.id , c.parent_tags
FROM
tags as c
INNER JOIN prod as p
ON c.parent_tags = p.id
)
SELECT
points.id,
points.name,
points.description,
/*points.info,*/
points.distance
from points
left join tags on points.tag_id = tags.id
where tags.name in (select prod.name from prod)
);
END;
$$ LANGUAGE plpgsql;
as a result i want see maybe set of 2 table or generator function that yield some intermediate result not shure how exacltly it should look
demo
CREATE OR REPLACE FUNCTION pg_temp.selectitemsbyroottag(tag_name text, _distance numeric)
RETURNS TABLE(id bigint, name text, description text, distance numeric, count bigint)
LANGUAGE plpgsql
AS $function$
DECLARE _sql text;
BEGIN
_sql := $p1$WITH RECURSIVE prod AS (
SELECT
tags.name, tags.id, tags.parent_tags
FROM
tags
WHERE tags.name ilike '%$p1$ || tag_name || $p2$%'
UNION
SELECT c.name, c.id , c.parent_tags
FROM
tags as c
INNER JOIN prod as p
ON c.parent_tags = p.id
)
SELECT
points.id,
points.name,
points.description,
points.distance,
count(*) over ()
from points
left join tags on points.tag_id = tags.id
where tags.name in (select prod.name from prod)
and points.distance > $p2$ || _distance
;
raise notice '_sql: %', _sql;
return query execute _sql;
END;
$function$
You can call it throug following way
select * from pg_temp.selectItemsByRootTag('test',20);
select * from pg_temp.selectItemsByRootTag('test_8',20) with ORDINALITY;
The 1 way to call the function, will have a row of total count total number of rows. Second way call have number of rows plus a serial incremental number.
I also make where q.distance < 400 into function input argument.
selectItemsByRootTag('test',20); means that q.distance > 20 and tags.name ilike '%test%'.

I am getting Dollar sign unterminated

I want to create a function like below which inserts data as per the input given. But I keep on getting an error about undetermined dollar sign.
CREATE OR REPLACE FUNCTION test_generate
(
ref REFCURSOR,
_id INTEGER
)
RETURNS refcursor AS $$
DECLARE
BEGIN
DROP TABLE IF EXISTS test_1;
CREATE TEMP TABLE test_1
(
id int,
request_id int,
code text
);
IF _id IS NULL THEN
INSERT INTO test_1
SELECT
rd.id,
r.id,
rd.code
FROM
test_2 r
INNER JOIN
raw_table rd
ON
rd.test_2_id = r.id
LEFT JOIN
observe_test o
ON
o.raw_table_id = rd.id
WHERE o.id IS NULL
AND COALESCE(rd.processed, 0) = 0;
ELSE
INSERT INTO test_1
SELECT
rd.id,
r.id,
rd.code
FROM
test_2 r
INNER JOIN
raw_table rd
ON rd.test_2_id = r.id
WHERE r.id = _id;
END IF;
DROP TABLE IF EXISTS tmp_test_2_error;
CREATE TEMP TABLE tmp_test_2_error
(
raw_table_id int,
test_2_id int,
error text,
record_num int
);
INSERT INTO tmp_test_2_error
(
raw_table_id,
test_2_id,
error,
record_num
)
SELECT DISTINCT
test_1.id,
test_1.test_2_id,
'Error found ' || test_1.code,
0
FROM
test_1
WHERE 1 = 1
AND data_origin.id IS NULL;
INSERT INTO tmp_test_2_error
SELECT DISTINCT
test_1.id,
test_1.test_2_id,
'Error found ' || test_1.code,
0
FROM
test_1
INNER JOIN
data_origin
ON
data_origin.code = test_1.code
WHERE dop.id IS NULL;
DROP table IF EXISTS test_latest;
CREATE TEMP TABLE test_latest AS SELECT * FROM observe_test WHERE 1 = 2;
INSERT INTO test_latest
(
raw_table_id,
series_id,
timestamp
)
SELECT
test_1.id,
ds.id AS series_id,
now()
FROM
test_1
INNER JOIN data_origin ON data_origin.code = test_1.code
LEFT JOIN
observe_test o ON o.raw_table_id = test_1.id
WHERE o.id IS NULL;
CREATE TABLE latest_observe_test as Select * from test_latest where 1=0;
INSERT INTO latest_observe_test
(
raw_table_id,
series_id,
timestamp,
time
)
SELECT
t.id,
ds.id AS series_id,
now(),
t.time
FROM
test_latest t
WHERE t.series_id IS DISTINCT FROM observe_test.series_id;
DELETE FROM test_2_error re
USING t
WHERE t.test_2_id = re.test_2_id;
INSERT INTO test_2_error (test_2_id, error, record_num)
SELECT DISTINCT test_2_id, error, record_num FROM tmp_test_2_error ORDER BY error;
UPDATE raw_table AS rd1
SET processed = case WHEN tre.raw_table_id IS null THEN 2 ELSE 1 END
FROM test_1 tr
LEFT JOIN
tmp_test_2_error tre ON tre.raw_table_id = tr.id
WHERE rd1.id = tr.id;
OPEN ref FOR
SELECT 1;
RETURN ref;
OPEN ref for
SELECT o.* from observe_test o
;
RETURN ref;
OPEN ref FOR
SELECT
rd.id,
ds.id AS series_id,
now() AS timestamp,
rd.time
FROM test_2 r
INNER JOIN raw_table rd ON rd.test_2_id = r.id
INNER JOIN data_origin ON data_origin.code = rd.code
WHERE o.id IS NULL AND r.id = _id;
RETURN ref;
END;
$$ LANGUAGE plpgsql VOLATILE COST 100;
I am not able to run this procedure.
Can you please help me where I have done wrong?
I am using squirrel and face the same question as you.
until I found that:
-- Note that if you want to create the function under Squirrel SQL,
-- you must go to Sessions->Session Properties
-- then SQL tab and change the Statement Separator from ';' to something else
-- (for intance //). Otherwise Squirrel SQL sends one piece to the server
-- that stops at the first encountered ';', and the server cannot make
-- sense of it. With the separator changed as suggested, you type everything
-- as above and end with
-- ...
-- end;
-- $$ language plpgsql
-- //
--
-- You can then restore the default separator, or use the new one for
-- all queries ...
--

Postgres find all rows in database tables matching criteria on a given column

I am trying to write sub-queries so that I search all tables for a column named id and since there are multiple tables with id column, I want to add the condition, so that id = 3119093.
My attempt was:
Select *
from information_schema.tables
where id = '3119093' and id IN (
Select table_name
from information_schema.columns
where column_name = 'id' );
This didn't work so I tried:
Select *
from information_schema.tables
where table_name IN (
Select table_name
from information_schema.columns
where column_name = 'id' and 'id' IN (
Select * from table_name where 'id' = 3119093));
This isn't the right way either. Any help would be appreciated. Thanks!
A harder attempt is:
CREATE OR REPLACE FUNCTION search_columns(
needle text,
haystack_tables name[] default '{}',
haystack_schema name[] default '{public}'
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
begin
FOR schemaname,tablename,columnname IN
SELECT c.table_schema,c.table_name,c.column_name
FROM information_schema.columns c
JOIN information_schema.tables t ON
(t.table_name=c.table_name AND t.table_schema=c.table_schema)
WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
AND c.table_schema=ANY(haystack_schema)
AND t.table_type='BASE TABLE'
--AND c.column_name = "id"
LOOP
EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text) like %L',
schemaname,
tablename,
columnname,
needle
) INTO rowctid;
IF rowctid is not null THEN
RETURN NEXT;
END IF;
END LOOP;
END;
$$ language plpgsql;
select * from search_columns('%3119093%'::varchar,'{}'::name[]) ;
The only problem is this code displays the table name and column name. I have to then manually enter
Select * from table_name where id = 3119093
where I got the table name from the code above.
I want to automatically implement returning rows from a table but I don't know how to get the table name automatically.
I took the time to make it work for you.
For starters, some information on what is going on inside the code.
Explanation
function takes two input arguments: column name and column value
it requires a created type that it will be returning a set of
first loop identifies tables that have a column name specified as the input argument
then it forms a query which aggregates all rows that match the input condition inside every table taken from step 3 with comparison based on ILIKE - as per your example
function goes into the second loop only if there is at least one row in currently visited table that matches specified condition (then the array is not null)
second loop unnests the array of rows that match the condition and for every element it puts it in the function output with RETURN NEXT rec clause
Notes
Searching with LIKE is inefficient - I suggest adding another input argument "column type" and restrict it in the lookup by adding a join to pg_catalog.pg_type table.
The second loop is there so that if more than 1 row is found for a particular table, then every row gets returned.
If you are looking for something else, like you need key-value pairs, not just the values, then you need to extend the function. You could for example build json format from rows.
Now, to the code.
Test case
CREATE TABLE tbl1 (col1 int, id int); -- does contain values
CREATE TABLE tbl2 (col1 int, col2 int); -- doesn't contain column "id"
CREATE TABLE tbl3 (id int, col5 int); -- doesn't contain values
INSERT INTO tbl1 (col1, id)
VALUES (1, 5), (1, 33), (1, 25);
Table stores data:
postgres=# select * From tbl1;
col1 | id
------+----
1 | 5
1 | 33
1 | 25
(3 rows)
Creating type
CREATE TYPE sometype AS ( schemaname text, tablename text, colname text, entirerow text );
Function code
CREATE OR REPLACE FUNCTION search_tables_for_column (
v_column_name text
, v_column_value text
)
RETURNS SETOF sometype
LANGUAGE plpgsql
STABLE
AS
$$
DECLARE
rec sometype%rowtype;
v_row_array text[];
rec2 record;
arr_el text;
BEGIN
FOR rec IN
SELECT
nam.nspname AS schemaname
, cls.relname AS tablename
, att.attname AS colname
, null::text AS entirerow
FROM
pg_attribute att
JOIN pg_class cls ON att.attrelid = cls.oid
JOIN pg_namespace nam ON cls.relnamespace = nam.oid
WHERE
cls.relkind = 'r'
AND att.attname = v_column_name
LOOP
EXECUTE format('SELECT ARRAY_AGG(row(tablename.*)::text) FROM %I.%I AS tablename WHERE %I::text ILIKE %s',
rec.schemaname, rec.tablename, rec.colname, quote_literal(concat('%',v_column_value,'%'))) INTO v_row_array;
IF v_row_array is not null THEN
FOR rec2 IN
SELECT unnest(v_row_array) AS one_row
LOOP
rec.entirerow := rec2.one_row;
RETURN NEXT rec;
END LOOP;
END IF;
END LOOP;
END
$$;
Exemplary call & output
postgres=# select * from search_tables_for_column('id','5');
schemaname | tablename | colname | entirerow
------------+-----------+---------+-----------
public | tbl1 | id | (1,5)
public | tbl1 | id | (1,25)
(2 rows)

SQL0107N The name "insert into OH09ZC1.cte3 with cte2 (list, cnt, cnt_max) AS (SELECT" is too long. The maximum length is "128"

Here is the procedure where I use a statement with temp table:
CREATE OR REPLACE PROCEDURE dept_query (
p_table CHAR(10),
p_date CHAR(10),
p_start CHAR(6)
)
LANGUAGE SQL
BEGIN
DECLARE v_table VARCHAR(128);
DECLARE v_colname VARCHAR(128);
DECLARE v_month CHAR(6);
DECLARE v_int integer default 0;
DECLARE stat VARCHAR(1000);
DECLARE stmt STATEMENT;
.......
set stat = 'insert into cte1 select colname, row_number() over() as row_nbr from syscat.columns where tabname = ?';
PREPARE stmt FROM stat;
execute stmt using p_table;
set stat = "insert into OH09ZC1.cte3 -- cte, cte1 & cte3 are ordinary tables
with cte2 (list, cnt, cnt_max) AS
(SELECT VARCHAR('', 32000), 0, count(colname) FROM OH09ZC1.cte1
UNION ALL
SELECT
case when cte2.list = '' THEN RTRIM(CHAR(cte1.colname))
else cte2.list || ', ' || RTRIM(CHAR(cte1.colname)) end,
cte2.cnt + 1,
cte2.cnt_max
FROM OH09ZC1.cte1, cte2
WHERE cte1.row_nbr = cte2.cnt + 1 AND cte2.cnt < cte2.cnt_max )
select list FROM cte2 where cte2.cnt = cte2.cnt_max fetch first 1 rows only";
PREPARE stmt FROM stat;
execute stmt;
......
END;
This gets me a list of the columns in a table.
The problem is that 'insert into OH09ZC1.cte3 with cte2 (list, cnt, cnt_max) AS ' doesn't contain any long names, so why do I get this error:
SQL0107N The name "insert into OH09ZC1.cte3 with cte2 (list, cnt, cnt_max) AS (SELEC" is too long. The maximum length is "128".
I also got the same error when 'insert into OH09ZC1.cte3' was not there.
set stat = "insert into... -- SQL string literals should use single quotation marks. Double quotation marks indicate an identifier, and "insert into cte3 ...", in addition to being too long for an identifier, is invalid anyway.

Creating a view of frequencies from a table with unknown number of columns

I have a table with n columns and I need to create a view which contains the frequencies of every unique value in every column. n is unknown since, I need to apply the solution on numerous tables with different number of columns.
For example i have table:
column1 column2 column3
value1 value2 value3
value2 value2 value1
value1 value2 value2
The view should be something like this:
columnname value frequency
column1 value1 2
column1 value2 1
column2 value2 3
...
Since I have very little experience with sql any help would be extremely appreciated.
Many thanks in advance!
Thus far I have come up with this but am sort of stonewalled now.
CREATE or REPLACE FUNCTION create_view () RETURNS setof record AS $$
DECLARE
col RECORD;
BEGIN
for col in execute 'select column_name from information_schema.columns
where table_name = ''table123''' LOOP
???
END LOOP;
return;
END;
$$
LANGUAGE 'plpgsql';
Simple SQL:
SELECT 'col1' AS col, col1 AS val, count(*) AS ct FROM tbl GROUP BY col1
UNION ALL
SELECT 'col2', col2, count(*) FROM tbl GROUP BY col2
UNION ALL
SELECT 'col3', col3, count(*) FROM tbl GROUP BY col3
PL/pqSQL function executing dynamic SQL:
CREATE OR REPLACE FUNCTION f_demo(_schema text, _tbl text)
RETURNS TABLE(col text, val text, ct bigint) AS
$xx$
DECLARE
_fld text;
_sql text := '';
BEGIN
FOR _fld IN
SELECT a.attname -- use quote_ident to safeguard against SQLi
FROM pg_catalog.pg_attribute a
WHERE a.attrelid = (COALESCE(_schema || '.', '') || _tbl)::regclass
AND a.attnum > 0
AND NOT a.attisdropped
-- AND a.attname ~~ '%col%' -- if you want to pick specific columns
LOOP
RETURN QUERY EXECUTE
'SELECT $1, ' || quote_ident(_fld) || '::text, count(*)
FROM ' || COALESCE(quote_ident(_schema) || '.', '') || quote_ident(_tbl) || '
GROUP BY 2'
USING _fld;
END LOOP;
END;
$xx$
LANGUAGE 'plpgsql';
Call:
SELECT * FROM f_demo('public', 'mytable');
Or, if you want to use the schema provided by search_path:
SELECT * FROM f_demo(NULL, 'mytable');
Major points
Works for any table and any number of columns with values of any type.
Values are cast to text to simplify my example. Could be done with a polymorphic type, too.
See this related answer for info on plpgsql techniques and links: https://stackoverflow.com/q/8146245/939860