SQL - Select Help - Case When? Return Value from Second Table?
Hi - next to folks on this board I am probably somewhere between a Beginner and an Intermediate SQL user.
Ive been using a case when statement in plsql to find "all those who's status in any program was cancelled during a specific time, but have become or are still active in a second program"
So, Im effectively trying to return a value from a second table in a case when, but its not liking anthing other than a declared text like 'Yes' or 'No'.
Here is the select statement - is there another way to do this where I can get the results I need?
case when pp.party_id in (select pp1.party_id -- Cancelled clients Active in another program
from asa.program_participation pp1,
asa.curr_prog_participation_status cpps1
where pp1.program_participation_id = cpps1.program_participation_id
and pp1.party_id = pp.party_id
and cpps1.code_value = 'ACT')
then 'Yes' else 'No' end as Active_in_Other_Prg
So - in place of 'Yes' i basically want the program that they are active in or pp1.program_id, else Null
It is possible that the client can be active in more than one program as well.
Any assistance is greatly appreciated, i explored with if's and decodes but I cant get anything to work.
Batesey
Sounds like an outer join. See ora doc: Joins
select p.*
, q.party_id
, q.program_id
from table_with_party_id p
, ( select pp1.party_id -- Cancelled clients Active in another program
, pp1.program_id
from asa.program_participation pp1,
asa.curr_prog_participation_status cpps1
where pp1.program_participation_id = cpps1.program_participation_id
and pp1.party_id = pp.party_id
and cpps1.code_value = 'ACT') q
where p.party_id = q.party_id ( +)
Note: In the example above there shoudn't be a space between the ( and +), but the forum software automagically converts this to
The outer join will link show all records from the p table and only records from q if the party_id matches, ie q.party_id and q.program_id will be null if there is no match.
edit: added program_id
Similar Messages
-
Need help for SQL SELECT query to fetch XML records from Oracle tables having CLOB field
Hello,
I have a scenario wherein i need to fetch records from several oracle tables having CLOB fields(which is holding XML) and then merge them logically to form a hierarchy XML. All these tables are related with PK-FK relationship. This XML hierarchy is having 'OP' as top-most root node and ‘DE’ as it’s bottom-most node with One-To-Many relationship. Hence, Each OP can have multiple GM, Each GM can have multiple DM and so on.
Table structures are mentioned below:
OP:
Name Null Type
OP_NBR NOT NULL NUMBER(4) (Primary Key)
OP_DESC VARCHAR2(50)
OP_PAYLOD_XML CLOB
GM:
Name Null Type
GM_NBR NOT NULL NUMBER(4) (Primary Key)
GM_DESC VARCHAR2(40)
OP_NBR NOT NULL NUMBER(4) (Foreign Key)
GM_PAYLOD_XML CLOB
DM:
Name Null Type
DM_NBR NOT NULL NUMBER(4) (Primary Key)
DM_DESC VARCHAR2(40)
GM_NBR NOT NULL NUMBER(4) (Foreign Key)
DM_PAYLOD_XML CLOB
DE:
Name Null Type
DE_NBR NOT NULL NUMBER(4) (Primary Key)
DE_DESC NOT NULL VARCHAR2(40)
DM_NBR NOT NULL NUMBER(4) (Foreign Key)
DE_PAYLOD_XML CLOB
+++++++++++++++++++++++++++++++++++++++++++++++++++++
SELECT
j.op_nbr||'||'||j.op_desc||'||'||j.op_paylod_xml AS op_paylod_xml,
i.gm_nbr||'||'||i.gm_desc||'||'||i.gm_paylod_xml AS gm_paylod_xml,
h.dm_nbr||'||'||h.dm_desc||'||'||h.dm_paylod_xml AS dm_paylod_xml,
g.de_nbr||'||'||g.de_desc||'||'||g.de_paylod_xml AS de_paylod_xml,
FROM
DE g, DM h, GM i, OP j
WHERE
h.dm_nbr = g.dm_nbr(+) and
i.gm_nbr = h.gm_nbr(+) and
j.op_nbr = i.op_nbr(+)
+++++++++++++++++++++++++++++++++++++++++++++++++++++
I am using above SQL select statement for fetching the XML records and this gives me all related xmls for each entity in a single record(OP, GM, DM. DE). Output of this SQL query is as below:
Current O/P:
<resultSet>
<Record1>
<OP_PAYLOD_XML1>
<GM_PAYLOD_XML1>
<DM_PAYLOD_XML1>
<DE_PAYLOD_XML1>
</Record1>
<Record2>
<OP_PAYLOD_XML2>
<GM_PAYLOD_XML2>
<DM_PAYLOD_XML2>
<DE_PAYLOD_XML2>
</Record2>
<RecordN>
<OP_PAYLOD_XMLN>
<GM_PAYLOD_XMLN>
<DM_PAYLOD_XMLN>
<DE_PAYLOD_XMLN>
</RecordN>
</resultSet>
Now i want to change my SQL query so that i get following output structure:
<resultSet>
<Record>
<OP_PAYLOD_XML1>
<GM_PAYLOD_XML1>
<GM_PAYLOD_XML2> .......
<GM_PAYLOD_XMLN>
<DM_PAYLOD_XML1>
<DM_PAYLOD_XML2> .......
<DM_PAYLOD_XMLN>
<DE_PAYLOD_XML1>
<DE_PAYLOD_XML2> .......
<DE_PAYLOD_XMLN>
</Record>
<Record>
<OP_PAYLOD_XML2>
<GM_PAYLOD_XML1'>
<GM_PAYLOD_XML2'> .......
<GM_PAYLOD_XMLN'>
<DM_PAYLOD_XML1'>
<DM_PAYLOD_XML2'> .......
<DM_PAYLOD_XMLN'>
<DE_PAYLOD_XML1'>
<DE_PAYLOD_XML2'> .......
<DE_PAYLOD_XMLN'>
</Record>
<resultSet>
Appreciate your help in this regard!Hi,
A few questions :
How's your first query supposed to give you an XML output like you show ?
Is there something you're not telling us?
What's the content of, for example, <OP_PAYLOD_XML1> ?
I don't think it's a good idea to embed the node level in the tag name, it would make much sense to expose that as an attribute.
What's the db version BTW? -
Help needed to merge values from two tables -
We have these three test tables shown, which have a common ID; And amount fields; I want the -------
test1.val = test2.val + test3.val
when they have common ids in them;
I have shown the test data below: And the expected output;
NOTE: In database with real table values - each of them have millions of rows in them. So effeciency is very important here;
SQL> desc test1;
Name Null? Type
ID NUMBER
VAL NUMBER
SQL> desc test2;
Name Null? Type
ID NUMBER
VAL NUMBER
SQL> desc test3;
Name Null? Type
ID NUMBER
VAL NUMBER
SQL> select * from test1;
ID VAL
1 50
2 50
3 55
4 60
5 20
5 rows selected.
SQL> select * from test2;
ID VAL
1 25
1 25
2 5
2 5
4 75
5 rows selected.
SQL> select * from test3;
ID VAL
1 25
1 25
2 5
2 25
2 25
5 10
6 rows selected.
I EXPECT the output to be:
SQL> select * from test1;
ID VAL
1 100
2 65
3 20
4 75
3 20
5 10
6 rows selected.Need help with the update queries - joining three tables -
-
SQL Select Performance - Approached to fetch data from big table
Hi
I just wanted to know view on different approached to fetch data from a table which has 40 billion records and which joined to another table which has 1 million record.
e.g.
I have two tables TableA and TableB
TableA has 40 Billion records has 6 columns
TableA has partitions on Date
TableA has required indexes
TableB has 1 Milluion record and has 10 columns
Table A has indexes
Now I have written query like
select distinct TableA.column1,TableA.column2,TableB.columnA
FROM TableA join TableB
ON TableA.Column1=TableB.Column2
WHERE TableA.DateColumn between StartDate and EndDate
for a given date range it will fetch 5 billion of records which takes around 40 minutes.
I just wanted to know what all tuning approaches I can follow. What would be the best approach to make record retrieval faster in such a scenario.
Just wanted to know your vies/experience in such a scenarioSufficiently large array fetchsize
and,
possibly using parallel query,
pop into my mind.
I would be interested though in the business requirement that asks for you to write a program that gets 5 billion (!) rows out of the database... -
Oracle / JDBC Error when Returning values from an Insert
I have a (oracle) table with a auto-incrementing id. From time to time I want to insert rows to this table, but want to be able to know what the pk of the newly inserted row is. One way I could do this is:
SQL> variable var1 number;
SQL> insert into test (name) values ('test value') returning id into :var1;
1 row created.
SQL> print var1;
13
As best as I can write it, that in java should be:
String query = "insert into test (name) values ('test') returning id into :var1";
OracleCallableStatement cs = (OracleCallableStatement) conn.prepareCall(query);
cs.registerOutParameter(1, OracleTypes.NUMBER );
cs.execute();
System.out.println(cs.getInt(1));
The problem is that when I run it, I get an error:
java.sql.SQLException: Protocol violation
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:764)
at oracle.jdbc.driver.T4CCallableStatement.doOall8(T4CCallableStatement.java:215)
at oracle.jdbc.driver.T4CCallableStatement.executeForRows(T4CCallableStatement.java:954)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1168)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3285)
at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:3390)
at oracle.jdbc.driver.OracleCallableStatement.execute(OracleCallableStatement.java:4223)
at restitution.shared.Sandbox2.run(Sandbox2.java:25)
at restitution.shared.Sandbox2.main(Sandbox2.java:11)
According to their website, this is (yet another) bug:
What does "Protocol Violation" mean?
The Thin driver throws this exception when it reads something from the RDBMS that it did not expect. This means that the protocol engine in the Thin driver and the protocol engine in the RDBMS are out of synch. There is no way to recover from this error. The connection is dead. You should try to close it, but that will probably fail too.
If you get a reproducible test case that generates this error, please file a TAR with Oracle Global Support. Be sure to specify the exact version numbers of the JDBC driver and the RDBMS, including any patches.
Can someone tell me what I'm doing wrong? Is there any other ways to do a insert / get key in one sql query ?I tried your solution, but it didn't work. I get an error (incorrect column number):
Caused by: java.sql.SQLException: Niepoprawny indeks kolumny
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameterInternal(OracleCallableStatement.java:121)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:283)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:363)
at (...).Row$1.createCallableStatement(Row.java:82)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:836)
... 69 more
The code is following:
String query = "BEGIN insert into movement (doc_number) values ('abc') returning id into :?; END;";
OracleCallableStatement cs = (OracleCallableStatement) c.prepareCall(query);
cs.registerOutParameter(1, OracleTypes.NUMBER);
cs.execute();
LOG.debug("result:"+ cs.getInt(1));
I used Oracle database 10.2.0.1 with jdbc thin driver ojdbc14.jar. Could you point out your configuration?
Regards,
Rafal Rusin
www.mimuw.edu.pl/~rrusin -
Query to table in Database Link returns value from local table
Hi
I made a databaselink (Create database link db_a.world connect to db_a identified by <user> using 'db_a.world')
Then I query a table, connected as a user in db_b.world (this is our developer database - identical to db_a): Select count(*) from table@db_a.world.
When I get the result - it comes from the database I am logged in to (db_b)! - This is easy to check, because when I run select count(*) from table - it shows the same number. When I connect to the remote database, the same query shows another (correct) number.
When I created the database link, Oracle demanded a loopback clause. Why is that, and can this be the reason for the strange behaviour?
Thanx
Anders
Narvik, NorwayHi Anders,
A loopback database link is when you want to test connecting to the same database as say a different user. It can be used for testing purposes. Creating a database link doesn't require a loopback clause. The reason why you are getting the same row count as db_b.world because db_a.world has been created as a loopback link.
In the example you have Create database link db_a.world connect to db_a identified by <user> using 'db_a.world' , the clause after 'connect to' is meant to be the username and the clause after 'identified by' is meant to be the password.
So, create a regular database link like this:
create database link db_a_link connect to <user> identified by <passwd> using <service name>
You shouldn't get an error message that the loopback clause has to be specified. Then try querying and hopefully it will work.
-Raj -
Selecting fields those which contains values from a table of one record
hello
Is it possible to select the fields of a table having not null values for a single record. The record contains 25 fields like
FieldNames are Field1, Field2......Field25
if Field1 and Field12 has some not null values and other fields contain null values, is it possible to retrieve these two fields...
Thanks for replies..
RinsonWhy wouldn't it be? What have you tried? What were your actual results vs. your expected results?
-
Script fails when passing values from pl/sql to unix variable
Script fails when passing values from pl/sql to unix variable
Dear All,
I am Automating STATSPACK reporting by modifying the sprepins.sql script.
Using DBMS_JOB I take the snap of the database and at the end of the day the cron job creates the statspack report and emails it to me.
I am storing the snapshot ids in the database and when running the report picking up the recent ids(begin snap and end snap).
From the sprepins.sql script
variable bid number;
variable eid number;
begin
select begin_snap into :bid from db_snap;
select end_snap into :eid from db_snap;
end;
This fails with the following error:
DB Name DB Id Instance Inst Num Release Cluster Host
RDMDEVL 3576140228 RDMDEVL 1 9.2.0.4.0 NO ibm-rdm
:ela := ;
ERROR at line 4:
ORA-06550: line 4, column 17:
PLS-00103: Encountered the symbol ";" when expecting one of the following:
( - + case mod new not null <an identifier>
<a double-quoted delimited-identifier> <a bind variable> avg
count current exists max min prior sql stddev sum variance
execute forall merge time timestamp interval date
<a string literal with character set specification>
<a number> <a single-quoted SQL string> pipe
The symbol "null" was substituted for ";" to continue.
ORA-06550: line 6, column 16:
PLS-00103: Encountered the symbol ";" when expecting one of the following:
( - + case mod new not null <an identifier>
<a double-quoted delimited-identifier> <a bind variable> avg
count current exists max min prior sql stddev su
But when I change the select statements below the report runs successfully.
variable bid number;
variable eid number;
begin
select '46' into :bid from db_snap;
select '47' into :eid from db_snap;
end;
Even changing the select statements to:
select TO_CHAR(begin_snap) into :bid from db_snap;
select TO_CHAR(end_snap) into :eid from db_snap;
Does not help.
Please Help.
TIA,
NischalHi,
could it be the begin_ and end_ Colums of your query?
Seems SQL*PLUS hs parsing problems?
try to fetch another column from that table
and see if the error raises again.
Karl -
Need of SQL query in selecting distinct values from two tables
hi,
I need a query for selecting distinct values from two tables with one condition.
for eg:
there are two tables a & b.
in table a there are values like age,sex,name,empno and in table b valuses are such as age,salary,DOJ,empno.
here what i need is with the help of empno as unique field,i need to select distinct values from two tables (ie) except age.
can anybody please help me.
Thanks in advance,
RatheeshNot sure what you mean either, but perhaps this will start a dialog:
SELECT DISTINCT a.empno,
a.name,
a.sex,
b.salary,
b.doj
FROM a,
b
WHERE a.empno = b.empno;Greg -
How to select distinct values from a table when it has composite primary ke
Hi
I have the requirement like , I need to select distinct one column values from the table which has composite primary key. How to acheive this functioinality using view object.
Eg : Table 1 has col1 and col2, col3
col1 col2 col3
1 A NA
1 B NA
2 A NA
3 C NA
2 D NA
primary key (col1,col2)
I have to select distinct col1.
ThanksHi
I got the solution for above. By Creating the read only view object we can acheive this.
thanks -
How to get return values from stored procedure to ssis packge?
Hi,
I need returnn values from my stored procedure to ssis package -
My procedure look like and ssis package .Kindly help me to oget returnn value to my ssis package
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [TSC]
-- Add the parameters for the stored procedure here
@P_STAGE VARCHAR(2000)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
--SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
truncate table [INPUTS];
INSERT
INTO
[INPUTS_BASE]
SELECT
[COLUMN]
FROM [INPUTS];
RETURN
END
and i am trying to get the return value from execute sql task and shown below
and i am taking my returnn value to result set variableYou need to have either OUTPUT parameters or use RETURN statement to return a value in stored procedures. RETURN can only return integer values whereas OUTPUT parameters can be of any type
First modify your procedure to define return value or OUTPUT parameter based on requirement
for details see
http://www.sqlteam.com/article/stored-procedures-returning-data
Once that is done in SSIS call sp from Execute SQL Task and in parameter mapping tabe shown above add required parameters and map them to variables created in SSIS and select Direction as Output or Return Value based on what option you used in your
procedure.
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
How to Sort by the length of the returned value from a query.
Hi,
I was wondering if it is possible to sort by the length of the returned value from a query?
For example if I want to get a list of people with the name 'Samuel', I would like to short by how short the length of the whole name is.
Sort by length of the name in SQL
Samuel Syda
Samuel Indranaka
Samuel Johnsons
Samuel Longhenderson
Thank you.Hi,
Sorting is done by an ORDER BY clause at the end of the main query.
In most cases, you can ORDER BY any expression, even f it is not in the SELECT clause. In this case, it sounds like you just need:
ORDER BY LENGTH (name_column)
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
Post your query, using an ORDER BY clause like the one above, and point out where that query is producing the wrong results, and explain, using specific examples, how you get the right results from the given data in those places.
Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
See the forum FAQ: https://forums.oracle.com/message/9362002 -
T-SQL and CLR types for return value do not match
Hi I am trying to create a CLR function to call a webservice, the CLR function return data type is double, whether I try
to create this as a table valued funcion or a scalar to return a distance travelled value I am receiving the error below. I've tried changing data types around in the CLR side and the SQL side but keep receiving the same error message, any help would be appreciated,
Thank you,
[Microsoft.SqlServer.Server.SqlFunction(Name = "DistanceCalc")]
public static Double DistanceCalc(Double SrcLat, Double SrcLong,
Double DestLat, Double DestLong)
MileageWS ws = new MileageWS();
ws.Url = "http://test.isp.ca/Distance.asmx";
int intUom = 0; // 0 = Mile, 1 = KM
RouteType RouteMethod = RouteType.Practical;
Requester RequestedFrom = Requester.LinkRoute;
Double distance;
distance = ws.GetDistanceInfoForLonLat(SrcLat, SrcLong, DestLat, DestLong, intUom, RouteMethod, RequestedFrom);
return distance;
CREATE FUNCTION DistanceCalc
@SrcLat as float, @SrcLong as float,
@DestLat as float, @DestLong as float
RETURNS TABLE (Distance float)
External NAME CLRfunctions.RIFunctions.DistanceCalc
GO
Error received when try to Create function ...
1, Level 16, State 2, Procedure pcMiler, Line 6
CREATE FUNCTION for "pcMiler" failed because T-SQL and CLR types for return value do not match.You defined at table-valued CLR function, but I think you meant to define a scalar CLR function. That might be the cause of the error.
RETURNS TABLE (Distance float)
should be
RETURNS (Distance float) -
Subprocess 33 was not successful. Master cannot read return value from S 33
Hi All,
We are on BI 7.0 SP 19.
We have submitted a planning sequence in the background with automatic packaging.
The planning sequence has two steps:
Step 1. Z_PLNG_FUNCTION1
Step 2. Z_PLNG_FUNCTION2
As per automatic packaging, the system chose 0ACCOUNT for packaging.
When submitted, each step has been submitted to 30 packages as 30 subprocesses.
For Step 1, the log shows that All subprocesses executed.
For Step 2, the log shows that the subprocess 33 and 58 failed, which means subprocess #3, and # 28 for the step 2 as the subprocess is numbered in the log in combination with step 1.
The messages in the log for the failed subprocesses are as follows:
@5C\QError@ Subprocess 33 was not successful
@5C\QError@ Master cannot read return value from subprocess 33
@5C\QError@ Subprocess 58 was not successful
@5C\QError@ Master cannot read return value from subprocess 58
Our question is on how to find the exact cause of the subprocess failure.
I tried to look for the details on the error messages, they have been not helpful.
What is meant by 'Master cannot read return value from subprocess' and how to get the exact cause of the failure?
Thanks in advance,
Best Regards,
- ShashiShashi,
implement the following notes and check again:1368659, 1525723, 1532061.
Regards,
Marc
SAP Techology RIG -
Capture Return Value from Contextual Events Subscriber Method
Hi
I was wondering if anyone knew whether you could capture the return value from a method exposed as a subscriber for a contextual event?
Requirement: We have 2 bounded task flows (parent-child) with the child task flow embedded as a region in a view activity in the parent task flow. Based on an action in the parent task flow we raise a contextual event which calls an application module method exposed as a data control within the child task flow. We need to be able to capture the return value from the method on the managed bean.
Example method within child task flow application module:
public String contextualEventSub(){
Return "Y";
So here we would like to capture String value when the event is raised by the event producer (parent task flow action).
Within the Event Map on the page definition of the parent task flow view activity it is possible to set parameters to pass to the subscriber but it’s not obvious where you can capture the return value.
Many thanks!
Technology:
ADF 11.1.1.7 – ADFbc with ADF task flows and page fragmentsCheck this URL it may help you
One size doesn't fit all: JDev 11g: Programmatic Contextual Events
Maybe you are looking for
-
Issues with adding a line....
Can someone PLEASE give me some course of action to take here. I feel extremely frustrated and upset with Verizon, and none of the reps seem to want to be of any assistance at all…… Recently, my wife and I decided that it was time to consolidate our
-
Unclear about requirements/information for Edge vs Contract plans.
I am currently on a 8GB/70 Shared data plan with a corporate discount. I have 4 smart phones and 2 iPads. My total bill is $241.60 + Taxes. Our contract on all 4 phones is now up as of 2/1/15. I have been asking questions about switching to the e
-
How do i import video from my sony cx130 to imovie
how do i import video from my sony cx130 to imovie?
-
Hi, I have created a smartform alongwith its driver program. I have attached it to the output type WA03. Whenever I create a delivery which automatically confirms a TO and creates a material document, the smartform should have got automatically trigg
-
R/3 extraction to 2 different systems (QA and PRD)
Hi, I have to make initial loads form R/3 to BW-QA and BW-PRD, my question is: I need to fill the setup tables for each system (one for QA and one for PRD) or just one is necessary??