I'm trying to do a case statement in an OpenEdge SQL-92 query that can have two columns defining the output.
SELECT
"PERSON"."First",
"PERSON"."Last",
"PERSON"."EmpCode" as EmployeeCode,
CASE "PERSON"."Building"
WHEN '111' then 'HQ'
WHEN '222' then 'OPS'
WHEN '111' AND "PERSON"."EmpCode" = 'CCLASS' then 'MGMT'
END as Location
FROM ....
The compound case is throwing a syntax error when I run the query. I know I can do this in MSSQL... I assume I can for OpenEdge as well?
Any thoughts on how this is accomplished in with OpenEdge SQL?
Proposed based on horse with no name's suggestion:
CASE
WHEN "PERSON"."Building" = '111' then 'HQ'
WHEN "PERSON"."Building" = '222' then 'OPS'
WHEN "PERSON"."Building" = '111' AND "PERSON"."EmpCode" = 'CCLASS' then 'MGMT'
END as Location
Related
In SQL Server, I can use IF conditional structure to execute some statements if a condition is true. According to this and this, there seem to be no such structure in SQLite.
I want to check if a table exist, if it does, do nothing, if not, do a lot of things including creating tables, inserting and deleting data from other tables and updating as well:
CASE WHEN ((SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'TraitsSwap') = 1) THEN
-- 50 lines of code, including CREATE, DROP, INSERT, DELETE and UPDATE statements, with random() in used
ELSE
-- Do nothing
END
Is there anyway I can achieve this? The code includes usage of random() and it requires consistent result (i.e, only random in the first time). I am sorry if this sounds unreasonable, but this is in context of game modding, so I cannot really change the backend code to run separated transaction code.
I think there may be an alternative if there is a function in SQLite that can execute a string/statement block and return a result. For that, I can transform the query into
SELECT CASE WHEN ((SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'TraitsSwap') = 1) THEN
ExecuteCode("Code; RETURN 1;")
ELSE
0
END
I tried
SELECT CASE WHEN ((SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'TraitsSwap') = 1) THEN
SELECT 1;
INSERT INTO Foo(Test) VALUES("");
SELECT "A";
ELSE
SELECT 1;
SELECT 2;
SELECT "A";
END
but it's unsuccessful, the error is
near "SELECT": syntax error: SELECT CASE WHEN ((SELECT COUNT(*) FROM
sqlite_master WHERE type = 'table' AND name = 'TraitsSwap') = 1) THEN
SELECT
My code follows:
SELECT COUNT(_id) AS count FROM general WHERE _id = 1 CASE WHEN count > 0 THEN UPDATE general SET userGivenId = 'xxx' WHERE _id = 1 ELSE INSERT INTO general (userGivenId) VALUES ('xxx' ) END
With the error:
android.database.sqlite.SQLiteException: near "CASE": syntax error: , while compiling: SELECT COUNT(_id) AS count FROM general WHERE _id = 1 CASE WHEN count > 0 THEN UPDATE general SET userGivenId = 'xxx' WHERE _id = 1 ELSE INSERT INTO general (userGivenId) VALUES ('xxx' ) END
This is the shortest query I will use. Why I do this is because my other queries will have rows that needs to be updated but some may not be touched. Using replace will replace all the data (at least that is how it works for me on my Android phone). For instance my File class will have a filePath, but sometimes the response from the server will return null and I am only to update the File IF the server returns a new File.
Did I forget to write anything?
SQLite does not have any control logic because this would not make sense in an embedded database (there is no separate server machine/process whose asynchronous execution could improve performance).
CASE can be used only for expressions, not for entire commands.
Handle the control logic in your app:
Cursor c = db.rawQuery("SELECT 1 FROM general WHERE _id = 1", null);
if (c.moveToFirst())
db.execSQL("UPDATE general SET userGivenId = 'xxx' WHERE _id = 1");
else
db.execSQL("INSERT INTO general (userGivenId) VALUES ('xxx')");
For these particular commands, if you have a unique constraint on the _id column (and a primary key is constrained to be unique), you can use the INSERT OR REPLACE command:
INSERT OR REPLACE INTO general(_id, userGivenId) VALUES(1, 'xxx')
I am trying to create dynamic table within procedure but i am getting error please
tell me whats the error
CREATE OR REPLACE PROCEDURE check_sms_bundle_25 (
MON VARCHAR2,
YEAR_P VARCHAR2 DEFAULT TO_CHAR (SYSDATE, 'YY'),
QUARTER VARCHAR2,
TYPE VARCHAR2 DEFAULT 'NEW')
IS
BEGIN
IF UPPER (QUARTER) = 1
THEN
EXECUTE IMMEDIATE 'BEGIN CREATE OR REPLACE TABLE (''SMS_Bundle_25_'''|| UPPER (MON)|| '''_Q'''|| UPPER (QUARTER)|| '||''_''||'''|| UPPER (YEAR_P)|| ''')
AS
SELECT customer_id, otxact
FROM ordertrailer INNER JOIN orderhdr_all ON ohxact = otxact
WHERE sncode = 343 AND ohentdate = ''1-aug-2014'' AND ohstatus = ''IN''
END';
END IF;
END;
The error msg is
ORA-06550: line 2, column 4: PLS-00103: Encountered the symbol
"CREATE" when expecting one of the following:
begin case declare exit for goto if loop mod null pragma raise
return select update while with << close current delete
fetch lock insert open rollback savepoint set sql execute commit
forall merge pipe ORA-06512: at "FI_SDINE.CHECK_SMS_BUNDLE_25", line 9
ORA-06512: at line 1
As well as 'or replace' not being valid as part of the create table syntax, you're enclosing the DDL statement inside another anonymous PL/SQL block, you're trying to put the table name inside parentheses, and you're including quote marks - which are not allowed in an (unquoted) object identifier. So if you pass in argukments AUG, 14, 1 NEW then your dynamic statement is trying to run:
BEGIN CREATE OR REPLACE TABLE ('SMS_Bundle_25_'AUG'_Q'1||'_'||'14')
AS
SELECT customer_id, otxact
FROM ordertrailer INNER JOIN orderhdr_all ON ohxact = otxact
WHERE sncode = 343 AND ohentdate = '1-aug-2014' AND ohstatus = 'IN'
END
The BEGIN/END make is a block and the DDL statement isn't valid in PL/SQL; that's why you're having to use execute immediate in the first place. If you change your construction to:
EXECUTE IMMEDIATE 'CREATE TABLE SMS_Bundle_25_'|| UPPER (MON)
|| '_Q'|| UPPER (QUARTER) ||'_' || UPPER (YEAR_P)|| '
AS
SELECT customer_id, otxact
FROM ordertrailer INNER JOIN orderhdr_all ON ohxact = otxact
WHERE sncode = 343 AND ohentdate = ''1-aug-2014'' AND ohstatus = ''IN''');
you'd then be trying to run:
CREATE TABLE SMS_Bundle_25_AUG_Q1_14
AS
SELECT customer_id, otxact
FROM ordertrailer INNER JOIN orderhdr_all ON ohxact = otxact
WHERE sncode = 343 AND ohentdate = '1-aug-2014' AND ohstatus = 'IN'
which at least looks more viable, assuming the tables you're selecting from exist. No idea why you're passing the year and quarter numbers as strings or applying upper() to them. And presumably you really want the select to be filtered on the same year and month as the table name.
It's useful to display the command you're trying to execute, for example with dbms_output, to see exactly what you've created; and you can then also run that manually to see where it's going wrong more clearly.
But as noted in comments, it's unusual to create objects from a procedure like this. Your schema should usually be static, not modified on the fly. You won't be able to refer to this table from other code unless that is also being built dynamically. You seem to be creating a table as a snapshot of the other tables; a view or a materialised view might be more appropriate. But I'm not really sure why you're doing this so it's not entirely clear what you should be doing instead.
I'm stuck with creating a view in Oracle, but before I create the view, I always test it first and I always got this error: Ora-00904.
This is the situation. I have this one Set of Query let say Query A that I need to combined using UNION ALL with the Query A itself with only few modifications applied to create another bigger Set of Query - Query B. The main constraint that keeps me on doing this is the Database Design, and I'm not in the position in the company to change it, so I have to adapt to it. Query A unions Query A for 6 times creating Query B. The additional Major constraint is Query B is from 1 database user only, but there are 54 database users with the same structures that I need to fetch the same query. Query B (db user1) unions Query B (db user2) unions Query B (db user3) and so on until 54 then finally creating Query C --- the final output. My scrip has already reached 6048 lines, then I got this problem that I don't get when I test Query A and Query B. All my table names, owner names, and column names are all correct but I got that error.
This is the code (that needs to be repeated for 54x6 times) - the Query A. Query B applies some similar modification only.:
Select
'2013' "YEAR",
Upper(a.text_month) "MONTH",
Upper('Budget') "VERSION",
case
when length(b.level1_name) > 5 then 'Parent'
else 'SUBSIDIARIES'
end "COMPANY_GROUP",
case
when length(b.level1_name) < 6 and b.level1_name <> '1000' then 'Subsidiaries'
else '1000 Parent'
end "COMPANY",
case
when length(b.level1_name) < 6 and b.level1_name <> '1000' then 'SUBS'
else '1000'
end "COMPANY_CODE",
case
when length(b.level1_name) > 5 then 'Parent'
else 'SUBSIDIARIES'
end "COMPANY_NAME",
b.level1_displayname "DIVISION",
b.level1_name "DIVISION_CODE",
case
when length(b.level1_name) > 5 then ltrim(upper(substr(b.level1_displayname, 8)))
else upper(ltrim(substr(b.level1_displayname, 10)))
end "DIVISION_NAME",
upper(a.text_nature_of_trip) "NATURE_OF_TRAVEL",
upper(a.text_placeeventstraining) "TRAVEL_DETAILS",
upper(a.text_country) "COUNTRY",
a.text_name_of_employee "EMPLOYEE_NAME", a.float_no_of_attendees "NO_OF_ATTENDEES",
a.text_sponsored "SPONSORED",
a.text_remarks "REMARKS",
'OTHER TRAVEL EXPENSES' "COST_ELEMENT",
a.FLOAT_702120005_OTHER_TRAVEL_E "AMOUNT"
From PUBLISH_PNL_AAAA_2013.et_travel_transaction a,
PUBLISH_PNL_AAAA_2013.cy_2elist b
Where a.elist = b.level3_iid
ORA-00904 is "invalid column name" -- either you've spelled the column name wrongly, or prefixed it with the wrong table alias, omitted quotes from a string literal, or any number of other issues.
Check the point in the code that the error message mentions for mistakes like that.
I have a stored function
CREATE OR REPLACE FUNCTION schedule(name in varchar2,pass in varchar2 )
begin
select t.name,s.starttime from traininfo t,schedule s, trainslot ts
where t.trainid in( select ts.trainid from trainslot
where ts.slotid in (select s.slotid from schedule s
where s.source='dhaka'
and s.dest='bogra' ))
end
I want to return this result set using a cursor.
I don't see where you are using either of the input parameters in your function. I'll assume that is either intentional or an oversight because you're simplifying the code. It also appears that your query is missing conditions to join between the traininfo, schedule, and trainslot tables in the outer query. It seems odd that your nested IN statements are turning around and querying the schedule and trainslot tables given this lack of join conditions. I don't know whether this is a result of copy-and-paste errors or something that was missed in posting the question or whether these are real problems. I'll make a guess at the query you're intending to write but if my guess is wrong, you'll have to tell us what your query is supposed to do (posting sample data and expected outputs would be exceptionally helpful for this).
CREATE OR REPLACE FUNCTION schedule(name in varchar2,pass in varchar2 )
RETURN sys_refcursor
is
l_rc sys_refcursor;
begin
open l_rc
for select t.name, s.starttime
from traininfo t,
schedule s,
trainslot ts
where t.trainid = ts.trainid
and s.slotid = ts.slotid
and s.source = 'dhaka'
and s.dest = 'borga';
return l_rc;
end;