Getting following error while creating stored procedure in PHPmyadmin sql box:
1064 - You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near ') BEGIN DECLARE ref_id varchar(10)' at line 1
CREATE PROCEDURE get_tree(IN id varchar)
BEGIN
DECLARE ref_id varchar(10);
DECLARE userid varchar(10);
SET userid = id;
SET ref_id='';
SELECT ref_id into ref_id
FROM user WHERE user_id=id ;
create TEMPORARY table IF NOT EXISTS temp_table as (select * from user where 1='');
truncate table temp_table;
WHILE ref_id <> '' DO
insert into temp_table select * from user WHERE user_id=userid;
SET userid = ref_id;
SET ref_id='';
SELECT ref_id into ref_id
FROM user WHERE user_id=userid;
END WHILE;
select * from temp_table;
END
The problem is the procedure parameter -- you cannot have varchar without the length. It should be
CREATE PROCEDURE get_tree(IN id varchar(10))
BEGIN
...
(or whatever length you want there, but 10 seems to be a reasonable choice).
Issue resolved by adding following delimiter as:
DELIMITER $$
CREATE PROCEDURE get_tree(IN id varchar(10))
BEGIN
DECLARE ref_id varchar(10);
DECLARE userid varchar(10);
SET userid = id;
SET ref_id='';
SELECT ref_id into ref_id
FROM user WHERE user_id=id ;
create TEMPORARY table IF NOT EXISTS temp_table as (select * from user where 1='');
truncate table temp_table;
WHILE ref_id <> '' DO
insert into temp_table select * from user WHERE user_id=userid;
SET userid = ref_id;
SET ref_id='';
SELECT ref_id into ref_id
FROM user WHERE user_id=userid;
END WHILE;
select * from temp_table;
END$$
DELIMITER ;
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
I have a grid that connected to AdoDataset. i want read records from two table with join SQL, but save record in a table.
Read data:
adodataset.commandtext := 'select * from Table1 left join Table2 on Table1.ID = Table2.ID';
adodataset.Open;
I want save Table1 Fields only when post
You can use ReadOnly property of DBGrid.Columns. For example if you have a query like this:
ADODataSet1.CommandText := 'SELECT * FROM Table1 JOIN Table2 ON Table1.ID = Table2.ID';
Then your DBGrid will be like:
You can then make 3rd and 4th columns read only at design time or at run time by these codes:
DBGrid1.Columns[2].ReadOnly := True;
DBGrid1.Columns[3].ReadOnly := True;
Also note that if you want to delete records only from Table1 then you should run this code when ADODataSet1 is active:
ADODataSet1.Properties['Unique Table'].Value := 'Table1';
Update:
As suggested in comments it's a good idea to set desired fields ReadOnly at DataSet level:
ADODataSet1.FieldByName('ID_1').ReadOnly := True;
ADODataSet1.FieldByName('Table2_Value').ReadOnly := True;
First of all the query example in the commandtext is wrong / ambiguous. I don't know what you want to perform but I'm guessing you want to change/save data in a table. In this case, why don't you perform the update in sql? Let's say you have the primary key field called "id", and you want to save a field called "name" with another value.
var
id, NewName: string;
//...
begin
//...
id := adodataset.fieldbyname('id').AsString;
adodataset.connection.execute(
'UPDATE table1 SET name = ' + quotedstr(NewName) + ' WHERE id = ' + quotedstr(id)
);
// refresh the records by closing and reopening the adodataset
adodataset.close;
adodataset.open;
// move to the wanted record
adodataset.Locate('id', id, []);
Why not use TAdoQuery ?
Qry.Close;
Qry.SQL.Clear;
Qry.SQL.Add("select * from Table1 left join Table2 on Table1.ID = Table2.ID");
Qry.Open;
while not Qry.EOF do
begin
[do stuff]
Qry.Next;
end;
I am getting incorrect count from a query ran inside a stored procedure.
When we run the same query ( after hard-coding the values of table name and schema name ) it gives the correct result.
Preliminary analysis , hints the fact that the query run inside the stored procedure is for some reason ignoring the second filter ( i.e where ... and ... , the second part is being ignored ).
CREATE OR REPLACE PROCEDURE dev.gp_count (tablename VARCHAR(256))
AS
$$ DECLARE schema_name VARCHAR(64);
table_name VARCHAR(128);
check_count_1 INT;
check_count_2 INT;
BEGIN
schema_name:= SPLIT_PART(tablename,'.',1);
table_name:= SPLIT_PART(tablename,'.',2);
check_count_1 := (select count(*) from information_schema.tables where table_schema = schema_name and table_name like '%' + table_name +'%');
raise info 'check_count_1 - %',check_count_1;
end;
$$
language plpgsql;
And calling the above procedure as-
call dev.gp_count ('dev.gp_test1');
The result obtained from stored procedure is -
Warnings:
check_count_1 - 925
If we run the same query after substituting the values for table name and schema then -
select count(*) from information_schema.tables where table_schema = 'dev' and table_name like '%gp_test1%';
RESULT -
count
3
Now investigating the issue further -
The count obtained from stored procedure is same as the count obtained from this query -
select count(*) from information_schema.tables where table_schema = 'dev';
RESULT-
count
925
My Guess -
So this hints that , maybe inside stored procedure the second filter condition is being ignored.
Besides helping me with other alternatives , please do help me find the reason behind this anomaly too .
Thanks in Advance.
I think your problem lies in 1) your string concatenation and 2) use of table_name as a variable:
check_count_1 := (select count(*) from information_schema.tables where table_schema = schema_name and table_name like '%' + table_name +'%');
PostgreSQL string concatenation uses ||, so it should look like this:
check_count_1 := (select count(*) from information_schema.tables where table_schema = schema_name and table_name like '%' || table_name || '%');
Try changing it to look like this:
CREATE OR REPLACE PROCEDURE gp_count (tablename VARCHAR(256))
AS
$$ DECLARE
schema_name VARCHAR(64);
table_name1 VARCHAR(128);
check_count_1 INT;
check_count_2 INT;
BEGIN
schema_name:= SPLIT_PART(tablename,'.',1);
table_name1:= SPLIT_PART(tablename,'.',2);
check_count_1 := (select count(*) from information_schema.tables f where table_schema = schema_name and f.table_name like '%' || table_name1 || '%');
raise info 'check_count_1 - %',check_count_1;
end;
$$
language plpgsql;
Disclosure: I work for EnterpriseDB (EDB)
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 stored procedure which takes a varchar parameter called P_LOCATIONS in Oracle. This locations parameter has location id's that are comma separated. In database locationId is a number.
Following sql query throws an Invalid number when there are more than one locations. I understand that because of comma its not able to convert a varchar into a number. How can I achieve this?
create or replace PROCEDURE GET_RAW_DATA
( P_LOCATIONS IN VARCHAR2,
Results OUT SYS_REFCURSOR
)AS
BEGIN
select * from tableName where LOCATION_ID IN ( P_LOCATIONS);
END GET_RAW_DATA;
The end result of what you are doing is this:
select * from tableName where LOCATION_ID IN ('1,2,3');
And what you need is this:
select * from tableName where LOCATION_ID IN (1,2,3);
So you can use this:
select * from tableName where LOCATION_ID in (
select regexp_substr(P_LOCATIONS,'[^,]+{1}',1,level)
from dual connect by level <= length(regexp_replace(P_LOCATIONS,'[^,]*')) + 1
);