I can't seem to make the to_date/to_char (var, 'ddmmyyyy') to work. How do I get it in this format. I've tried to change the select as the output, all giving me errors.
Any help much appreciated!
DECLARE
auditnr NUMBER(7) := 186725;
pap_combinatie NUMBER(3) := 986;
gids VARCHAR(240) := 'G-040V.5';
begindatum date;
einddatum date;
maxeinddatum date;
operatorid number;
BEGIN
SELECT
-- Tried: to_date(MAX(aa.datum_begin_validatie),'ddmmyyyy'),
-- Tried: to_char(MAX(aa.datum_begin_validatie),'ddmmyyyy'),
MAX(aa.datum_begin_validatie),
max(aa.datum_eind_validatie),
max(aa.datum_eind_max),
max(o.operator_id)
INTO begindatum, einddatum, maxeinddatum, operatorid
FROM autocontrole2.activiteit_audit aa,
autocontrole2.pap_operator o
WHERE aa.pap_operator_id = o.pap_operator_id
AND aa.audit_oci_id = auditnr;
DBMS_OUTPUT.PUT_LINE(begindatum || ',' || einddatum || ',' || maxeinddatum || ',' || operatorid);
-- Tried: DBMS_OUTPUT.PUT_LINE(to_date(begindatum,'ddmmyyyy') || ',' || einddatum || ',' || maxeinddatum || ',' || operatorid);
-- Tried: DBMS_OUTPUT.PUT_LINE(to_char(begindatum,'ddmmyyyy') || ',' || einddatum || ',' || maxeinddatum || ',' || operatorid);
END;
Everything is giving me errors.
The OUTPUT is: 22-NOV-20,21-NOV-23,21-NOV-23,4775291
The output I want: 22112020, 21112023, 21112023, 4775291
To convert datatype DATE to VARCHAR2, use TO_CHAR. TO_DATE is used to convert a string (VARCHAR2) to a DATE.
So in your code that would become:
DBMS_OUTPUT.PUT_LINE(TO_CHAR(begindatum, 'DDMMYYYY')||...
Related
I need to create search (like '%-99' or like '%NON%')---there for all tables in SYS in DB2 in all columns --below code
---please for help--this is test code---but I have DB2 Database Error: ERROR [42703] [IBM][DB2/LINUXX8664] SQL0206N "WHERE" is not valid in the context where it is used.
DECLARE GLOBAL TEMPORARY TABLE SESSION.TEMP_DINAMIC_TEST_SEARCH
(
TABSET VARCHAR(128)
, TABSCHEMA VARCHAR(128)
, TABNAME VARCHAR(128)
, COLUMN_NAME VARCHAR(128)
, ROW_COUNT BIGINT
)
ON COMMIT PRESERVE ROWS NOT LOGGED
;
BEGIN
FOR C AS CUR CURSOR WITH HOLD FOR
SELECT 'INSERT INTO SESSION.TEMP_DINAMIC_TEST_SEARCH SELECT '''
||''' ,''' || TABLE_SCHEM || ''',''' || TABLE_NAME || ''',''' || COLUMN_NAME || ''', COUNT( DISTINCT(' || COLUMN_NAME || ')) FROM '
|| '"' || TABLE_SCHEM || '"."' || TABLE_NAME|| '"' ||WHERE|| '"' || COLUMN_NAME || '"' || LIKE || '"' ||'%-99'|| '"' || AS S
FROM SYSIBM.SQLCOLUMNS
WHERE TABLE_SCHEM = 'DWD' AND TABLE_NAME LIKE 'T_X_%'
WITH UR
DO
EXECUTE IMMEDIATE C.S;
COMMIT;
END FOR;
END
Wrong expression is used.
Try this:
SELECT
'INSERT INTO SESSION.TEMP_DINAMIC_TEST_SEARCH SELECT '''
|| ''' ,''' || TABLE_SCHEM || ''',''' || TABLE_NAME || ''',''' || COLUMN_NAME || ''', COUNT( DISTINCT(' || COLUMN_NAME || ')) FROM '
|| '"' || TABLE_SCHEM || '"."' || TABLE_NAME|| '" WHERE "' || COLUMN_NAME || '" LIKE ''%-99''' AS S
FROM SYSIBM.SQLCOLUMNS
WHERE TABLE_SCHEM = 'DWD' AND TABLE_NAME LIKE 'T_X_%'
/*
AND
(
TYPE_NAME LIKE '%CHAR'
OR TYPE_NAME LIKE '%GRAPHIC'
OR TYPE_NAME LIKE '%CLOB'
)
*/
WITH UR
BTW,
It's worth to generate the INSERT SELECT statements for string columns only as shown in the commented out lines.
Try not to use tables in the SYSIBM schema in Db2 for LUW - they are not documented and their content may be changed with some new release / fixpack without any notice. Use SYSCAT views instead - the SYSCAT.COLUMNS view in your case.
i have below tables and functions while executing the below function in postgresql ,it is showing ERROR: schema "tblmark" does not exist.Please help.
CREATE TABLE "LandXML_QCC_ParcelMarks"("DPID" TEXT,"From" TEXT,"Name" TEXT);
INSERT INTO "LandXML_QCC_ParcelMarks" VALUES ('1','ram','kumar');
CREATE TABLE "LandXML_QCC_ParcelInformation"("DPID" TEXT,"Pntref" TEXT)
INSERT INTO "LandXML_QCC_ParcelInformation" VALUES ('1','ram');
CREATE OR REPLACE FUNCTION GetParcelNonParcel(PlanID TEXT)
RETURNS TEXT AS $GetParcelNonParcel$
DECLARE
tblMark RECORD;
parCount INTEGER;
parNonCount INTEGER;
totalParNonCount TEXT;
tblCou INTEGER;
BEGIN
parCount=0;
parNonCount=0;
FOR tblMark IN (SELECT * FROM "LandXML_QCC_ParcelMarks" WHERE "DPID" = PlanID) LOOP
SELECT COUNT(*) INTO tblCou FROM "LandXML_QCC_ParcelInformation"
WHERE "DPID"=PlanID
AND (
"Pntref" LIKE '%' || tblMark.From || ',' || tblMark.Name '%'
OR
"Pntref" LIKE '%' || tblMark.Name || ',' || tblMark.From '%'
);
RAISE NOTICE 'Value: %', tblCou;
IF tblCou > 0 THEN
parCount = parCount + 1;
RAISE NOTICE 'Value: %', parCount;
ELSE
parNonCount = parNonCount + 1;
END IF;
END LOOP;
totalParNonCount = CAST(parCount AS TEXT) || ',' || CAST(parNonCount AS TEXT);
RAISE NOTICE 'Value: %', totalParNonCount;
RETURN totalParNonCount;
END;
$GetParcelNonParcel$ LANGUAGE plpgsql;
select GetParcelNonParcel('1');
While executing above function,it is showing ERROR: schema "tblmark" does not exist.
In your SELECT inside the FOR loop, you have the following condition:
... AND (
"Pntref" LIKE '%' || tblMark.From || ',' || tblMark.Name '%'
OR
"Pntref" LIKE '%' || tblMark.Name || ',' || tblMark.From '%'
)
You are missing the concatenation-operator || for the trailing '%' both times. Also, you are not properly referencing the columns of your record. Since you established them with " (double-quotes), you will always need to refer to them exactly the same way (This is a reason why you should not do this. So if it is not to late, change it to names without quotes.).
Using your momentary columnnames, this should help you:
... AND (
"Pntref" LIKE '%' || tblMark."From" || ',' || tblMark."Name" || '%'
OR
"Pntref" LIKE '%' || tblMark."Name" || ',' || tblMark."From" || '%'
)
I have this code and I want to concatenate the variables but don't work.
This is my DDL code for the view:
CREATE OR REPLACE function acd.add_credito2()
RETURNS void
SET SCHEMA 'acd'
SET search_path = acd
AS $$
DECLARE
auxsigla text;
auxnome text;
_sql text := 'CREATE OR REPLACE VIEW acd.teste AS SELECT md.matriz_disciplina_id AS id, dcp.nome, mc.curso, mc.versao AS matriz';
_join text := ' FROM matriz_disciplina as md LEFT JOIN disciplina as dcp ON md.disciplina_id = dcp.disciplina_id LEFT JOIN matriz_curricular as mc ON md.matriz_curricular_id = mc.matriz_curricular_id';
BEGIN
select into auxsigla, auxnome from ( select sigla, nome from acd.categoria_credito where categoria_credito_id = 9) as foo;
_join := _join || ' LEFT JOIN (SELECT creditos, matriz_disciplina_id FROM acd.disciplina_credito WHERE categoria_credito_id = ' || x || ') AS ' || "auxsigla" ' ON ' || "auxsigla" || '.matriz_disciplina_id = md.matriz_disciplina_id';
_sql := _sql || ', ' || "auxsigla" || '.' || auxnome || ' AS ' || auxnome;
_sql := _sql || _join;
EXECUTE _sql;
END;
$$ LANGUAGE plpgsql
So, when I execute the function
database-1=# select acd.add_credito2();
This error appears:
ERROR: type "auxsigla" does not exist
LINE 1: ...WHERE categoria_credito_id = ' || x || ') AS ' || "auxsigla"...
^
QUERY: SELECT _join || ' LEFT JOIN (SELECT creditos, matriz_disciplina_id FROM acd.disciplina_credito WHERE categoria_credito_id = ' || x || ') AS ' || "auxsigla" ' ON ' || "auxsigla" || '.matriz_disciplina_id = md.matriz_disciplina_id'
CONTEXT: PL/pgSQL function add_credito2() line 13 at assignment
Can anyone help me? I don't know what to do now.
(I know, this study view don't have a purpose but this is the idea that I want to use in the real view)
The error comes from this construct:
"auxsigla" ' ON '
You forgot a concatenation operator || between these two tokens, and now the SQL parser interprets it as
data_type string_constant
which is a way to specify constants of a certain data type.
Working examples would be DATE '2018-09-20' or INTEGER '-20'.
Your function has numerous other problems, two of which I could spot:
select into auxsigla, auxnome from will always set the variables to NULL because you forgot to specify which columns you want to select.
you do not properly escape single quotes while composing your dynamic query string. What if auxsigla has the value with'quote?
Use format() or quote_literal() and quote_ident() for that.
I need to generate Insert script in postgres for all the tables in a database such that it can be run again without throwing any error.
The problem is, Only few tables have primary key while the rest have Unique index on different columns.
This is why I am not able to list out the columns on which unique index has been created.
The reason behind this is that the schema is automatically created through Magnolia.
Can anyone help me write the query which produces Insert statement including 'Where not Exists (Select 1 from table where column = value)' condition based on Primary Key/Unique columns?
You can use on conflict:
insert into t ( . . . )
values ( . . . )
on conflict do nothing;
This function returns Insert script for data and works well with tables on which primary constraint is not available.
I have modified the code that I found on another thread by adding the condition to it.
CREATE OR REPLACE FUNCTION public.generate_inserts(varSchema text, varTable text) RETURNS TABLE(resultado text) AS $$
DECLARE CODE TEXT;
BEGIN
CODE :=
(
SELECT
'SELECT ''INSERT INTO '
|| table_schema || '.'
|| table_name ||' ('
|| replace(replace(array_agg(column_name::text)::text,'{',''),'}','') || ') SELECT ''||'
|| replace(replace(replace(array_agg( 'quote_nullable(' || column_name::text || ')')::text,'{',''),'}',''),',',' || '','' || ')
|| ' || '' Where Not Exists (Select 1 From ' || table_name ||' Where 1 = 1 '
|| ''''
|| replace(replace(replace(replace(array_agg(' || '' and (' || column_name::text || ' = '' || quote_nullable(' || column_name::text || '),' || ' || '' or ' || column_name::text || ' is null)''')::text,'{',''),'}',''),'"',''),',','')
|| '|| '');'''
|| ' FROM ' || table_schema || '.' || table_name || ';'
FROM information_schema.columns c
WHERE table_schema = varSchema
AND table_name = varTable
GROUP BY table_schema, table_name);
RETURN QUERY
EXECUTE CODE;
END;
$$ LANGUAGE plpgsql;
I am trying to construct a string from a table. I need to construct a string from each row and then concatenate these strings (with an appropriate separator) together. In a simple example the select produces a table with 3 rows; however, I get the message above.
Can anyone help? Thanks
for mFiles in
select url || pth || basename || '/' || basename || '.2.' || clientname into fName from files
where ( userId is null or uid != userId ) and (url is not null) and (pth is not null)
order by RANDOM() limit nImages LOOP
res := res || fName || '|';
RAISE NOTICE ' fName: % ' , fName;
END LOOP;
The problem was 'into fName'. Replacing this by 'as fName' and writing
res:= res || mFiles.fName || '|';
fixed the problem. Don't understand why exactly but ...
Following from Craig Ringer's suggestion, what if you remove the limit clause and instead break out of the loop with code like this (which would both test whether limit is the culprit and provide a good workaround):
idx := 1
for mFiles in
select url || pth || basename || '/' || basename || '.2.' || clientname into fName from files
where ( userId is null or uid != userId ) and (url is not null) and (pth is not null)
order by RANDOM()
LOOP
res := res || fName || '|';
RAISE NOTICE ' fName: % ' , fName;
IF idx = nImages THEN
EXIT
END IF;
END LOOP;
With the addition of declaring idx in the appropriate section higher up in the code.