How to create a user defined function in sybase? - user-defined-functions

I trying to define a function in sybase. I write this script:
CREATE FUNCTION GetUserGroup (userId int)
RETURNS int
BEGIN
RETURN (10)
END
but when I run this, I get this error:
>[Error] Script lines: 1-6 --------------------------
Incorrect syntax near the keyword 'BEGIN'.
Msg: 156, Level: 15, State: 2
Server: NEWSERVER, Procedure: GetUserGroup, Line: 3
>[Error] Script lines: 1-6 --------------------------
A RETURN statement with a return status may only be used in a SQL stored procedure.
Msg: 178, Level: 15, State: 1
Server: NEWSERVER, Procedure: GetUserGroup, Line: 4
[Executed: 10/13/09 11:01:29 AM IRST ] [Execution: 0/ms]
What can I do?
Thanks

I searched very much in web and other documents, I find that user-defined functions in Adaptive Server Enterprise 12 (ASE) must be implemented in Java.
I decided to use a StordProcedure. It usage is a little hard but it supported in all version of Sybase.
see: http://www.sypron.nl/udf.html

I doesn't find any thing wrong with the code. you can re-try with the code below-
CREATE FUNCTION GetUserGroup (userId int)
RETURNS int
As
BEGIN
RETURN (10)
END

Try This ....it will work
CREATE FUNCTION GetUserGroup (#userId int)
RETURNS int
As
BEGIN
declare #Result int
select #Result=10
RETURN #Result
END

this worked for me.
CREATE FUNCTION GetUserGroup (#userId int)
RETURNS int
AS
BEGIN
select #userId = 10
RETURN #userId
END

Related

Write custom H2 DB function Java

I am trying to run the below code using H2DB (via junit test), while doing so i get error message as below. I understand that, there are no function available as "days" in H2. So i am trying to write a custom function, but it does not work out, can any one help on writing this function.
SQLBuilder class code:
public String dummy() {
return new StringBuilder(new SQL() {
{
SELECT("date(CREATE_TMS)");
SELECT("CASE WHEN date(CREATE_TMS) >= (CURRENT DATE - cast('1' AS integer) days) THEN 'Y' ELSE 'N' END NEW_B");
FROM("Q.DUMMY");
}
}.toString().concat(" FOR READ ONLY WITH UR")).toString();
}
Error message:
org.springframework.jdbc.BadSqlGrammarException:
### Error querying database. Cause: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "SELECT DATE(CREATE_TMS), CASE WHEN DATE(CREATE_TMS) >= (CURRENT DATE - CAST('1' AS INTEGER) DAYS[*]) THEN 'Y' ELSE 'N' END NEW_BILLING
FROM Q.DUMMY FOR READ ONLY WITH UR "; expected "[, ::, *, /, %, +, -, ||, ~, !~, NOT, LIKE, ILIKE, REGEXP, IS, IN, BETWEEN, AND, OR, ,, )"; SQL statement:
SELECT date(CREATE_TMS), CASE WHEN date(CREATE_TMS) >= (CURRENT DATE - cast('1' AS integer) days) THEN 'Y' ELSE 'N' END NEW_BILLING
FROM Q.DUMMY FOR READ ONLY WITH UR [42001-199]
For some reason days are converted to DAYS[*], we can see that in error message.
Customer method i tried in schema-db2.sql:
drop ALIAS if exists days;
CREATE ALIAS days as '
import java.lang.String;
#CODE
java.lang.String days() throws Exception {
return "days";
}
';
applicaiton.properties:
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false;Mode=DB2
DAYS is not a function and is not a something that other databases support. Db2 also uses non-standard interval literals.
If you can build H2 from its current sources, you can use cast('1' AS integer) day in it (not the days) and such construction is also supported by Db2. You can also simply use 1 DAY, it is supported by current H2 and Db2 too.
(CURRENT_DAY - 1 DAY)
Sources of H2 are available on GitHub:
https://github.com/h2database/h2database
Building instructions are here:
https://h2database.com/html/build.html#building
You need a jar target.
To compile H2 from the current sources you need JDK 8, 9, 10, 11, or 12. Compiled jar will be compatible with more recent versions.

"Commands out of sync" error when trying to execute a procedure in MySQL 8

When executing below code in phpMyAdmin:
use db;
DELIMITER $$
DROP PROCEDURE IF EXISTS McaTest3$$
CREATE PROCEDURE McaTest3()
BEGIN
SELECT
cl.*
FROM `condition_library` cl
LEFT JOIN condition_custom cc on cl.condition_library_id = cc.condition_library_id
and cc.active = 1
AND (cc.permit_application_id = 20231 OR cc.permit_id = NULL)
WHERE FIND_IN_SET(cl.`condition_library_id`, '13070')
AND cl.active = 1
and cc.condition_library_id IS NULL;
END$$
DELIMITER ;
call McaTest3();
Getting error:
Error
Static analysis:
1 errors were found during analysis.
Missing expression. (near "ON" at position 25)
SQL query: Edit Edit
SET FOREIGN_KEY_CHECKS = ON;
MySQL said: Documentation
#2014 - Commands out of sync; you can't run this command now
This happens when there is no record found in the table which is at LEFT JOIN.
When the same is ran in MySQL Workbench: NO ERROR and return empty dataset.
Same procedure when executed from Application (Appian) is failing as well… Any clues?
Another question on Stackoverflow answered my issue:
link: MySQL error #2014 - Commands out of sync; you can't run this command now

Flyway callbacks with Oracle compile

I try to add before migration and after migration scripts as callbacks to flyway for compiling my views, procedures, functions etc.
Is there a possibility to stop it before a migration process or have a rollback when before or after scripts fail (or rather return a warning)?
Cause the only thing I see right now is I receive warnings like this
[WARNING] DB: Warning: execution completed with warning (SQL State: 99999 - Error Code: 17110)
and it goes on, without stopping.
I thought about FlywayCallback interface and it's implementation but I'm not entirely sure how it should be done with compiling.
I'm using Spring Boot 1.2.5 with the newest Flyway.
I have also same error. SQL State: 99999 - Error Code: 17110. i found this solution.
check which version under this warning and that version under sql script check have Trigger or any procedure which not closed properly.
close trigger or any procedure if oracle DB / end of trigger.
ex:
CREATE OR REPLACE TRIGGER Print_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON Emp_tab
FOR EACH ROW
WHEN (new.Empno > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :new.sal - :old.sal;
dbms_output.put('Old salary: ' || :old.sal);
dbms_output.put(' New salary: ' || :new.sal);
dbms_output.put_line(' Difference ' || sal_diff);
END;
/
Flyway 5.0 now comes with a feature called Error Handlers that lets you do exactly this. You can now create an error handler that turns that warning into an error as simply as
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.errorhandler.Context;
import org.flywaydb.core.api.errorhandler.ErrorHandler;
import org.flywaydb.core.api.errorhandler.Warning;
public class OracleProcedureFailFastErrorHandler implements ErrorHandler {
#Override
public boolean handle(Context context) {
for (Warning warning : context.getWarnings()) {
if ("99999".equals(warning.getState()) && warning.getCode() == 17110) {
throw new FlywayException("Compilation failed");
}
}
return false;
}
}
More info in the docs: https://flywaydb.org/documentation/errorhandlers
I had the same error when my scripts had a "CREATE TABLE XXX AS SELECT..." statement.
I fixed it by splitting it into two separate statements:
CREATE TABLE XXX (columns def...);
INSERT INTO TABLE XXX (columns...)
SELECT...;

How to parse this JSON where name has ','

I run next example
declare
obj json := json('{"TR,A" : "OK" }');
begin
dbms_output.put_line(JSON_EXT.GET_STRING (obj, 'TR,A'));
end;
and receive a message
ORA-20110: JSON Path parse error: expected . or [ found , at position 4
ORA-06512: at "SCOTT.JSON_EXT", line 193
ORA-06512: at "SCOTT.JSON_EXT", line 201
What is the work around?
The following code works for me:
declare
my_json json := json('{"TR,A" : "OK" }');
begin
dbms_output.put_line(my_json.get('TR,A').to_char);
end;
You should work directly with the JSON type. You should only have to resort to using packages like JSON_EXT if the type methods are insufficient for your use case.

BCB: from BDE to dbexpress, BCD exception

I'm having some problem about TSQLStoredProcedure. Here is the code:
storedproc->ParamByName("A")->AsInteger = adataset->FieldByName("AA")->AsInteger;
storedproc->ExecProc();
param "A" is declared integer in the form (and it's 29 in the program). Also the stored procedure has no errors. I'm sure of it. Database is Oracle 11g. By the way, as storedproc is executed an exception occurred:
...
EBcdException with message '<0000001:000000010000000:00000063612>' is not a valid BCD value
...
All was working fine with BDE but now, using dbexpress, there is this problem. I searched over the internet for some days and I did not find an answer.
I thank you in advance and beg a pardon for my English.
Francesco
Update
I searched over the web. I found something interesting at:
https://forums.codegear.com/thread.jspa?messageID=43223&tstart=0
http://www.delphigroups.info/2/8/750511.html
I decide to make some test:
SQLQuery->ParamByName("f1")->AsString = Edit1->Text;
SQLQuery->ExecSQL();
It works. Not the same for
SQLQuery->ParamByName("f1")->AsInteger = StrToInt(Edit1->Text); //ERROR DBX Error: Invalid Field Type.
SQLQuery->ParamByName("f1")->AsFloat = StrToFloat(Edit1->Text); //ERROR DBX Error: Invalid Field Type.
SQLQuery->ParamByName("f1")->AsBCD = StrToInt(Edit1->Text); //ERROR ORA-06502: PL/SQL: error: ... ORA-06512: at line 1.
SQLQuery->ParamByName("f1")->AsFMTBCD = StrToBcd(Edit2->Text); //ERROR ORA-06502: PL/SQL: error: ... ORA-06512: at line 1.
or by using TSQLStoredProc.
So now I call my pl/sql stored proc by TSQLQuery. I use "AsString" to pass values to parameters. Weird. How does dbexpress map types? Thanks in advance.

Resources