SELECT statement with 'IN'
Hi,
If SELECT statement has IN in the where clause, does that use the index?
For example,
SELECT t1 f2 f4 from ztest
WHERE
fid IN s_id AND
doctype IN s_doctype AND
year IN s_year .
What is the other option to optimize the SELECT with IN?
Thanks & regards,
Yogita
Moderator message - Please search before asking - post locked
Rob
Similar Messages
-
I m trying to find if LIMIT is a part of the select statement and if works like
set rowcount 1 in sybase....if anyone can post the generic select statement with LIMIT in it that would be great!
any help or input will be greatly appreciated
Thanks!Hallo,
i don't know sybase, but it is probably rownum
select * from scott.emp
where rownum < 3
Regards
Dmytro -
A Select statement with Appending table statement in it.
Hi,
How can I use a select statement with a <Appening table> statement in it.
SELECT DISTINCT <field Name>
FROM <DB table name>
APPENDING TABLE <itab>
WHERE <fieldname> EQ <Itab1-fieldname>
AND <fieldname> EQ <itab2-fieldname>.
Can I use the above select statement.If I'm using this...how this works?
Regards
DharmarajuHi, Dharma Raju Kondeti.
I found this in the SAP online help, hope this can help you.
Specifying Internal Tables
When you read several lines of a database table, you can place them in an internal table. To do this, use the following in the INTO clause:
SELECT ... INTO|APPENDING [CORRESPONDING FIELDS OF] TABLE <itab>
[PACKAGE SIZE <n>] ...
The same applies to the line type of <itab>, the way in which the data for a line of the database table are assigned to a table line, and the CORRESPONDING FIELDS addition as for flat work areas (see above).
The internal table is filled with all of the lines of the selection. When you use INTO, all existing lines in the table are deleted. When you use APPENDING; the new lines are added to the existing internal table <itab>. With APPENDING, the system adds the lines to the internal table appropriately for the table type. Fields in the internal table not affected by the selection are filled with initial values.
If you use the PACKAGE SIZE addition, the lines of the selection are not written into the internal table at once, but in packets. You can define packets of <n> lines that are written one after the other into the internal table. If you use INTO, each packet replaces the preceding one. If you use APPENDING, the packets are inserted one after the other. This is only possible in a loop that ends with ENDSELECT. Outside the SELECT loop, the contents of the internal table are undetermined. You must process the selected lines within the loop.
Regards,
feng.
Edited by: feng zhang on Feb 21, 2008 10:20 AM -
How to avoid data repetation when using select statements with innerjoin
how to avoid data repetation when using select statements with innerjoin.
thanks in advance,
satheeshyou can use a query like this...
SELECT DISTINCT
frg~prc_group1 "Product Group 1
frg~prc_group2 "Product Group 2
frg~prc_group3 "Product Group 3
frg~prc_group4 "Product Group 4
frg~prc_group5 "Product Group 5
prc~product_id "Product ID
txt~short_text "Product Description
UP TO 10 ROWS
INTO TABLE l_i_data
FROM
Joining CRMM_PR_SALESG and
COMM_PR_FRG_ROD
crmm_pr_salesg AS frg
INNER JOIN comm_pr_frg_rod AS prd
ON frgfrg_guid = prdfragment_guid
Joining COMM_PRODUCT and
COMM_PR_FRG_ROD
INNER JOIN comm_product AS prc
ON prdproduct_guid = prcproduct_guid
Joining COMM_PRSHTEXT and
COMM_PR_FRG_ROD
INNER JOIN comm_prshtext AS txt
ON prdproduct_guid = txtproduct_guid
WHERE frg~prc_group1 IN r_zprc_group1
AND frg~prc_group2 IN r_zprc_group2
AND frg~prc_group3 IN r_zprc_group3
AND frg~prc_group4 IN r_zprc_group4
AND frg~prc_group5 IN r_zprc_group5.
reward it it helps
Edited by: Apan Kumar Motilal on Jun 24, 2008 1:57 PM -
How to use a select statement with chinese characters?
I am currently developing a java servlet<using tomcat 4.x> which allows me to use select statement to retrieve results from the Microsoft SQL Server 2000 database. I am using a simple form to get the parameter for querying. The main problem i'm facing is that there are chinese information in the SQL database, but i can't retrieve it through the sql statement with the chinese characters input<thru the form with the help of NJ STAR>in the WHERE condition. When i execute the statement, it returns me no results even though the rows are present in the database.
Does anyone have the solution to using chinese words in the WHERE clause of the select statement to retrieve results with columns which contains chinese characters? Please help me. Thanks everyone. :)
PS: when i cut and paste those characters in the sql database and paste onto java.. it is ??? in questionmarks.. but when i paste them into excel 2000.. its shown as chinese chars again..
please heelppp~~Greetings,
PS: when i cut and paste those characters in thesql
database and paste onto java.. it is ??? in
questionmarks.. but when i paste them into excelThis is why the SELECT is not returning any results.
You need to set the character encoding set on your
statement and parameters for the characters to be
properly translated. Refer to the charsetName
parameter in the String class constructor in your API
docs and also to
$JDK_DOCS/guide/intl/encoding.doc.html in your JDK
documentation.
2000.. its shown as chinese chars again..Because Office programs are performing the same kind
of character translation with the appropriate MS APIs.
please heelppp~~Regards,
Tony "Vee Schade" Cookis it possible for you to show me some coding examples? i don't really understand what is to be done in order to set the char set and what does it really do.. tried reading up but still dun understand.. :(
pardon my shallow knowledge of java..
ok..
The thing is when i used an insert statement with chinese characters of GBK format hardcoded into the java servlet and then i use the insert statement to insert the chars into the database, it cannot be seen as a chinese word when i off the NJStar. and then it can be searched out with my current form of servlet.. below is my coding of the servlet..
note: i've set my html file to charset = GBK
//prototype of Search engine...
//workable for GBK input and output...
import java.io.*;
import java.io.OutputStream;
import java.io.IOException;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.util.*;
import java.sql.*;
import java.nio.charset.Charset;
public class SearchBeta extends HttpServlet {
private Vector musicDetails = new Vector();
private String query = "";
public void service (HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException, UnsupportedEncodingException {
query = req.getParameter ("T1");
System.out.println("before:"+query);
String type = req.getParameter ("D1");//type
query = req.getParameter ("T1");
//query = "������";
System.out.println("after:"+query);
getResults(type,query);
System.out.println("locale = :"+req.getLocale());
res.setContentType ("text/html;charset=GBK");
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<body bgcolor = \"black\">");
out.println("<font face = \"comic sans ms\" color=\"Cornsilk\">");
if (query.length()==0)
out.println ("Please key in your search query.");
else if (musicDetails.size()==0)
out.println ("Sorry, no results matching your search can be found.");
else {
out.println("<center>");
out.println("<table cellspacing = \"50\">");
int i = 0;
//Display the details of the music
while (i<musicDetails.size()) {
Results details = (Results)musicDetails.get(i);
String dbArtist = "";
String dbAlbum = "";
String dbTitle = "";
String dbCompany = "";
dbAlbum = details.getAlbum();
dbTitle = details.getTitle();
dbCompany = details.getCompany();
dbArtist = details.getArtist();
try{
dbAlbum = new String(dbAlbum.getBytes("ISO-8859-1"),"GBK");
dbTitle = new String(dbTitle.getBytes("ISO-8859-1"),"GBK");
dbCompany = new String(dbCompany.getBytes("ISO-8859-1"),"GBK");
dbArtist = new String(dbArtist.getBytes("ISO-8859-1"),"GBK");//correct translation.
catch(UnsupportedEncodingException e){
System.out.print(e);
e.printStackTrace();
String dbImage_loc = details.getImage();
out.println("<tr>");
out.println("<td><table>");
out.println("<img src=C:\\Program Files\\Apache Group\\Tomcat 4.1\\webapps\\examples\\ThumbNails\\"+dbImage_loc+">");
out.println("<tr>");
out.println("<th><font color=\"violet\"> Artist: </font></th>");
out.println("<td><font color=\"Cornsilk\">"+dbArtist+"</font></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th><font color=\"violet\"> Title: </font></th>");
out.println("<td><font color=\"Cornsilk\">"+dbTitle+"</font></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th><font color=\"violet\"> Company: </font></th>");
out.println("<td><font color=\"Cornsilk\">"+dbCompany+"</font></td>");
out.println("</tr>");
System.out.println("album: "+ dbAlbum);
out.println("<tr>");
out.println("<th><font color=\"violet\"> Album: </font></th>");
out.println("<td><font color=\"Cornsilk\">"+dbAlbum+"</font></td>");
out.println("</tr>");
System.out.println("company: "+ dbCompany);
out.println("</table></td>");
out.println("</tr>");
i++;
out.println("</table>");
out.println("</center>");
out.println("</font>");
out.println("</body>");
out.println("</head>");
out.println("</html>");
out.close();
//to remove all the elements from the Vector
musicDetails.removeAllElements();
//get Searched Music Details and store in Results object which is stored in musicDetails vector
public void getResults (String type, String searchQuery) {
try {
Class.forName ("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=music","sa","kokkeng");
Statement stmt = con.createStatement();
String query = "SELECT * FROM MusicDetails WHERE "+type+" = '"+searchQuery+"'";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String artist = rs.getString("Artist");
String title = rs.getString("Song");
String company = rs.getString("Company");
String album = rs.getString("Album");
String image_loc = rs.getString("Image");
Results details = new Results (artist,title,company,album,image_loc);
musicDetails.add(details);
stmt.close();
con.close();
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
with the above servlet i created, i can search out the data in the database which i've inserted through the insert statement. I still can't search for things i've keyed into the database directly using NJStar..
thank you so much for helping.. really hope any one else who knows the answer to this will reply too... thank you all so much...
-KK -
Incorrect SELECT statement with single quotes
I am getting the following error trying to select a value from a database:
SQLException caught: [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'mod='Payroll''. Couldn't load driver:[Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'mod='Payroll''.
Here is the select statement code:
PreparedStatement ps = con.prepareStatement("SELECT username FROM experts WHERE mod='"+mod+"'");
I have tried all kinds of variations with the quotes, and single quotes but still get the same error...I know I'm on the right track but I can't seem to spot the error and was hoping someone else could??
thanks in advance,
chukHi,
I tried that and now I get an even stranger syntax error which says "Syntax error (missing operator) in query expression 'mod=Pa_RaM000'."
any ideas? -
How to speed a select statement with the NOT EXISTS where condition ?
Hi all,
I created a view : create or replace view view_name as select * from table_1,table_2 where join_condition and some conditions.
Now I have added in the view "where" clause two NOT EXISTS conditions based on one another different table respectively.
Before I added these two conditions the response time was fast ; but after I added these two conditions then the response time deteriorated.
So how to optimize the select statement ? Hints and so on ...
Thank you very much indeed
Message was edited by:
andrianiainaJust run the script :
SQL> explain plan for select * from dual;
Explained.
SQL> @$ORACLE_HOME/rdbms/admin/utlxpls.sql
PLAN_TABLE_OUTPUT
| Id | Operation | Name | Rows | Bytes | Cost |
| 0 | SELECT STATEMENT | | | | |
| 1 | TABLE ACCESS FULL | DUAL | | | |
Note: rule based optimization
9 rows selected.
SQL>Nicolas. -
Join a SELECT-Statement with a INDEX
can I force a SELECT-Statement to use a certain Table-INDEX?
f.e.
select * from table a
where a.key like '%p'
..forced index a.idx.--Yes. You can.
Use SQL hint.
select /*+ index (tablename indexname) */.
If the index is usable-Oracle will use it. If not -Oracle will see it as a remark. -
Generating SQL SELECT statement with Schema
I develop a 3rd-party application that connects to various
databases via ODBC. Our program generates the SQL statement
so that the user does not have to. When connecting to oracle the
user often gets the error message: ORA-00942: table or view does
not exist.
To work around this our tech support department has tells the
customer to enter in the Schema name before the table name.
Thus,
SELECT ItemNo from Item
becomes
SELECT ItemNo from MySchema.Item
Is there a way that I can query the Data Source to find out
the Schema name so that our program can put in in the
statement. Is there a SQLGetInfo call I can make to get
this information?
Or, should I have the Server specified in the connection
string? For SQL Server we use SQLGetPrivateProfileString to
obtain the server name and then include it in the connection
string: SRVR=<servername>
Unfortunately, if this is the case the keyword is different
depending on the ODBC Driver involved. "Server" for Microsoft.
"SRVR" for Intersolv. "ServerName" for Oracle.
Note: We do not have Oracle in-house to test with. I'm
wondering if we could get Oracle for free for development
purposes.
Any and all information would be greatly appreciated.Thanks for the tip. I just finished downloading Oracle.
One user is able to successfully view the database with the
statement:
SELECT ItemNo from Item
But if another user tries it he gets the "table or view not
found" message. Changing the statement as follows will allow
the 2nd user to view the database:
SELECT ItemNo from "MAXIMO".Item
I want my application to query the database via ODBC for the
"MAXIMO" string so I can create the correct SQL statement.
Thanks!
<<Are you trying to view tables from a non-default schema?>>I don't know. You would know better than me from my
description. -
Dynamic select-statement with ranges
Good morning experts,
I just wanted to know if this is possible:
I had a report with a selection-screen where I can enter a table-name and one ore more filed-names (separated by ;).
After that, I create a table like my entered (for example MARA)
CREATE DATA gt_table TYPE TABLE OF (p_tab).
ASSIGN gt_table->* TO <gt_table>.
Then I split my entered fields (at and for each filed I made a selection (with function COMPLEX_SELECTIONS_DIALOG).
Result of this is for each field a range-tab which I write in a new table - first column is the name of the field, second column is a range-tab:
TYPES: BEGIN OF t_ranges,
sign TYPE tkeppllevs-sign,
opt TYPE tkeppllevs-opt,
low TYPE rsdslow,
high TYPE rsdslow,
END OF t_ranges.
DATA: BEGIN OF gs_conditions,
fieldname TYPE string,
ranges TYPE TABLE OF t_ranges.
DATA: END OF gs_conditions.
DATA: gt_conditions LIKE TABLE OF gs_conditions.
Now I want to make a select on the entered table (MARA).
So I make a loop on my gt_conditions:
LOOP AT gt_conditions INTO gs_conditions.
l_index = sy-tabix.
CONCATENATE 'gt_conditions[' l_index ']-ranges' INTO l_condition.
CONDENSE l_condition NO-GAPS.
CONCATENATE gs_conditions-fieldname 'IN' l_condition INTO lt_condition SEPARATED BY space.
IF sy-tabix > 1.
CONCATENATE 'AND' lt_condition INTO lt_condition SEPARATED BY space.
ENDIF.
APPEND lt_condition.
ENDLOOP.
If I look at it after the loop, it looks correct:
MATNR IN gt_conditions[1]-ranges
AND ERSDA IN gt_conditions[2]-ranges
But this wont work because of "gt_conditions[1]-ranges". I know, i can work with the "table in table", because gs_conditions-ranges works (I already tested this).
Has anybody any idea how to make my idea work?@Hymavathi:
Error is the following:
An exception occurred that is explained in detail below.
The exception, which is assigned to class 'CX_SY_DYNAMIC_OSQL_SEMANTICS', was
not caught and
therefore caused a runtime error.
The reason for the exception is:
The current ABAP program has tried to execute an Open SQL statement
which contains a WHERE, ON or HAVING condition with a dynamic part.
The part of the WHERE, ON or HAVING condition specified at runtime in
a field or an internal table, contains the invalid value
"GT_CONDITIONS[1]-RANGES".
@Hymavathi, second time:
This is the whole code for the select:
LOOP AT gt_conditions INTO gs_conditions.
l_index = sy-tabix.
CONCATENATE 'gt_conditions[' l_index ']-ranges' INTO l_condition.
CONDENSE l_condition NO-GAPS.
CONCATENATE gs_conditions-fieldname 'IN' l_condition INTO lt_condition SEPARATED BY space.
IF sy-tabix > 1.
CONCATENATE 'AND' lt_condition INTO lt_condition SEPARATED BY space.
ENDIF.
APPEND lt_condition.
ENDLOOP.
SELECT * FROM (p_tab)
INTO TABLE <gt_table>
WHERE (lt_condition).
You can see, the select is after the loop. So gs_conditions-ranges wouldn't be right, then the where statement would only use the last range-tab from my table gt_conditions. (loop at...endloop => gs-conditions-range = last gt_conditions-range). -
Select statement with if condition in cursors
Create procedure test (t1 in varchar2 ,t2 out varchar2)
IS
BEGIN
IF t1 = 'E'
select ENO INTO t2 from emp ;
elsif t1 = 'D'
select DNO INTO t2 from dept ;
end if;
end
how do i write this using cursorsi think i have to go for two cursors Intially i have written like the below codeThis requirement merely made me think of a pure SQL solution - something interesting...
As I mentioned, you likely should be using ref cursors as typically this requirement extends to a client that wants to make a call to Oracle without needing to know SQL or table names, pass parameters, and get a dynamic "+result set+" in response.
In Oracle. this is done using ref cursors. The code will look something like this"
{code}
create or replace procedure FooProc( someVar1 varchar2, someVar2 number, curResult OUT sys_refcursor ) is
begin
case
when someVar1 = someValueA then
open curResult for select * from emp;
when someVar1 = someValueB then
open curResult for select * from emp where empid = someVar2;
.. etc ..
end case;
end;
{code}
This is pretty straight forward stuff - and well explained with examples in the Oracle® Database PL/SQL User's Guide and Reference (http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/sqloperations.htm#sthref139)
You procedure it a tad different in output parameters (and not what one typically would get in a production system), but the concept is the same. If the SQL projection is the same for each cursor, you can use a ref cursor as above - and then simply code a single fetch to get the row's columns, close the cursor, and then return that column values as output parameters.
Edited by: Billy Verreynne to fix the broken Jive s/w that does not understand how to parse a link and show it correctly.. (am getting more and more peeved at the crappiness factor of the new forum s/w) -
What is syntax for inner join of Select statement with Secondary Index
Hi Genies,
Here i have created the Secondary index for table COEP and also used for select query but there is no improvement in runtime . taking same time for select query without index as well as with index. my code is
SELECT * INTO CORRESPONDING FIELDS OF TABLE ITAB_COEP FROM COEP AS A
INNER JOIN COBK AS B ON ( A~BELNR = B~BELNR AND A~KOKRS = B~KOKRS AND A~GJAHR = B~GJAHR )
WHERE A~OBJNR = OBJNR
AND A~GJAHR = CURRY
AND B~GJAHR = CURRY
AND A~RBEST = ''
AND A~BEKNZ = 'S'
AND B~BELNR NE WA_COBK-BELNR
AND B~AWREF_REV = ''
AND B~AWORG_REV = ''
AND B~KOKRS = WA_COIOB-KOKRS
AND B~BLDAT BETWEEN START_DATE AND END_DATE
AND B~BLART IN ('SA','KA','KR','AB') %_HINTS ORACLE 'INDEX("COEP" "COEP~ZBU")'.
index name is ZBU.
please any one let me know is there any syntax mistakes? but while checking and during the runtime it does'nt shows any error.
Regards,
Thangam.PHi Genies,
Here i have created the Secondary index for table COEP and also used for select query but there is no improvement in runtime . taking same time for select query without index as well as with index. my code is
SELECT * INTO CORRESPONDING FIELDS OF TABLE ITAB_COEP FROM COEP AS A
INNER JOIN COBK AS B ON ( A~BELNR = B~BELNR AND A~KOKRS = B~KOKRS AND A~GJAHR = B~GJAHR )
WHERE A~OBJNR = OBJNR
AND A~GJAHR = CURRY
AND B~GJAHR = CURRY
AND A~RBEST = ''
AND A~BEKNZ = 'S'
AND B~BELNR NE WA_COBK-BELNR
AND B~AWREF_REV = ''
AND B~AWORG_REV = ''
AND B~KOKRS = WA_COIOB-KOKRS
AND B~BLDAT BETWEEN START_DATE AND END_DATE
AND B~BLART IN ('SA','KA','KR','AB') %_HINTS ORACLE 'INDEX("COEP" "COEP~ZBU")'.
index name is ZBU.
please any one let me know is there any syntax mistakes? but while checking and during the runtime it does'nt shows any error.
Regards,
Thangam.P -
How to do an insert with a select statement, with unique values
Hi,
I have an insert statement like this
INSERT INTO TABLEA (ID, zzz
SELECT sequence.nextval, zzz FROM TABLEB
The problem is TABLEA won't allow any duplicates and TABLEB will return duplicates. Yet I can't use the distinct keyword since I am using a sequence.
Thanks.Samuel411 wrote:
Hi,
I have an insert statement like this
INSERT INTO TABLEA (ID, zzz
SELECT sequence.nextval, zzz FROM TABLEB
The problem is TABLEA won't allow any duplicates and TABLEB will return duplicates. Yet I can't use the distinct keyword since I am using a sequence.
Thanks.Why not?
drop sequence s
create sequence s;
create table distincting (col1 number, object_owner varchar2(30));
TUBBY_TUBBZ?
insert into distincting
select s.nextval, object_owner
from
select
distinct
owner as object_owner
from dba_objects
9 );
37 rows created.
TUBBY_TUBBZ? -
HOW CAN I USE MULTIPLE INNERJOINS IN A SINGLE SELECT STATEMENT?
HI,
I AM SHABEER AHMED,
I AM GETTING AN ERROR WHILE I ATTEMPT TO EXECUTE A SELECT STATEMENT WITH MULTIPLE INNER JOINS . BECOZ I WANT TO FETCH ITEM DATA, PARTNER DATA BASED ON HEADER DATA .
THEN OF COURSE I HAVE FETCH DATA FROM VBAK VBAP VBKD SO LZ SEND ME THE SOLUTION.
BYEHi,
1.Just see this:
SELECT * INTO CORRESPONDING FIELD OF TABLE itab
FROM t1 INNER JOIN t2 ON t1f4 EQ t2f4
INNER JOIN t3 ON t2f5 EQ t3f5 AND
t2f6 EQ t3f6 AND
t2f7 EQ t3f7.
2.But better to use for all entries.It increases the performance.
FOR ALL ENTRIES
Tabular Conditions
The WHERE clause of the SELECT statement has a special variant that allows you to derive conditions from the lines and columns of an internal table:
SELECT ... FOR ALL ENTRIES IN <itab> WHERE <cond> ...
<cond> may be formulated as described above. If you specify a field of the internal table <itab> as an operand in a condition, you address all lines of the internal table. The comparison is then performed for each line of the internal table. For each line, the system selects the lines from the database table that satisfy the condition. The result set of the SELECT statement is the union of the individual selections for each line of the internal table. Duplicate lines are automatically eliminated from the result set. If <itab> is empty, the addition FOR ALL ENTRIES is disregarded, and all entries are read.
The internal table <itab> must have a structured line type, and each field that occurs in the condition <cond> must be compatible with the column of the database with which it is compared. Do not use the operators LIKE, BETWEEN, and IN in comparisons using internal table fields. You may not use the ORDER BY clause in the same SELECT statement.
You can use the option FOR ALL ENTRIES to replace nested select loops by operations on internal tables. This can significantly improve the performance for large sets of selected data.
Example for ALL ENTRIES
DATA: TAB_SPFLI TYPE TABLE OF SPFLI,
TAB_SFLIGHT TYPE SORTED TABLE OF SFLIGHT
WITH UNIQUE KEY TABLE LINE,
WA LIKE LINE OF TAB_SFLIGHT.
SELECT CARRID CONNID
INTO CORRESPONDING FIELDS OF TABLE TAB_SPFLI
FROM SPFLI
WHERE CITYFROM = 'NEW YORK'.
SELECT CARRID CONNID FLDATE
INTO CORRESPONDING FIELDS OF TABLE TAB_SFLIGHT
FROM SFLIGHT
FOR ALL ENTRIES IN TAB_SPFLI
WHERE CARRID = TAB_SPFLI-CARRID AND
CONNID = TAB_SPFLI-CONNID.
LOOP AT TAB_SFLIGHT INTO WA.
AT NEW CONNID.
WRITE: / WA-CARRID, WA-CONNID.
ENDAT.
WRITE: / WA-FLDATE.
ENDLOOP.
INNER JOINS
In a relational database, you normally need to read data simultaneously from more than one database table into an application program. You can read from more than one table in a single SELECT statement, such that the data in the tables all has to meet the same conditions, using the following join expression:
SELECT...
FROM <tab> INNER JOIN <dbtab> AS <alias> ON <cond> <options>
where <dbtab> is a single database table and <tab> is either a table or another join expression. The database tables can be specified statically or dynamically as described above. You may also use aliases. You can enclose each join expression in parentheses. The INNER addition is optional.
A join expression links each line of <tab> with the lines in <dbtab> that meet the condition <cond>. This means that there is always one or more lines from the right-hand table that is linked to each line from the left-hand table by the join. If <dbtab> does not contain any lines that meet the condition <cond>, the line from <tab> is not included in the selection.
The syntax of the <cond> condition is like that of the WHERE clause, although individual comparisons can only be linked using AND. Furthermore, each comparison must contain a column from the right-hand table <dbtab>. It does not matter on which side of the comparison it occurs. For the column names in the comparison, you can use the same names that occur in the SELECT clause, to differentiate columns from different database tables that have the same names.
The comparisons in the condition <cond> can appear in the WHERE clause instead of the ON clause, since both clauses are applied equally to the temporary table containing all of the lines resulting from the join. However, each join must contain at least one comparison in the condition <cond>.
Example for INNER JOINS
REPORT demo_select_inner_join.
DATA: BEGIN OF wa,
carrid TYPE spfli-carrid,
connid TYPE spfli-connid,
fldate TYPE sflight-fldate,
bookid TYPE sbook-bookid,
END OF wa,
itab LIKE SORTED TABLE OF wa
WITH UNIQUE KEY carrid connid fldate bookid.
SELECT pcarrid pconnid ffldate bbookid
INTO CORRESPONDING FIELDS OF TABLE itab
FROM ( ( spfli AS p
INNER JOIN sflight AS f ON pcarrid = fcarrid AND
pconnid = fconnid )
INNER JOIN sbook AS b ON bcarrid = fcarrid AND
bconnid = fconnid AND
bfldate = ffldate )
WHERE p~cityfrom = 'FRANKFURT' AND
p~cityto = 'NEW YORK' AND
fseatsmax > fseatsocc.
LOOP AT itab INTO wa.
AT NEW fldate.
WRITE: / wa-carrid, wa-connid, wa-fldate.
ENDAT.
WRITE / wa-bookid.
ENDLOOP.
Regards,
Shiva Kumar(Reward if helpful). -
How to use bind variable in this select statement
Hi,
I have created this procedure where table name and fieldname is variable as they vary, therefore i passed them as parameter. This procedure will trim leading (.) if first five char is '.THE''. The procedure performs the required task. I want to make select statement with bind variable is there any possibility to use a bind variable in this select statement.
the procedure is given below:
create or replace procedure test(tablename in varchar2, fieldname IN varchar2)
authid current_user
is
type poicurtype is ref cursor;
poi_cur poicurtype;
sqlst varchar2(250);
THEVALUE NUMBER;
begin
sqlst:='SELECT EMPNO FROM '||TABLENAME||' WHERE SUBSTR('||FIELDNAME||',1,5)=''.THE ''';
DBMS_OUTPUT.PUT_LINE(SQLST);
OPEN POI_CUR FOR SQLST ;
LOOP
FETCH POI_CUR INTO THEVALUE;
EXIT WHEN POI_CUR%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(THEVALUE);
SQLST:='UPDATE '||TABLENAME|| ' SET '||FIELDNAME||'=LTRIM('||FIELDNAME||',''.'')';
SQLST:=SQLST|| ' WHERE EMPNO=:X';
DBMS_OUTPUT.PUT_LINE(SQLST);
EXECUTE IMMEDIATE SQLST USING THEVALUE;
END LOOP;
COMMIT;
END TEST;
Best Regards,So you want to amend each row individually? Is there some reason you're trying to make this procedure run as slow as possible?
create or replace procedure test (tablename in varchar2, fieldname in varchar2)
authid current_user
is
sqlst varchar2 (250);
thevalue number := 1234;
begin
sqlst := 'update ' || tablename || ' set ' || fieldname || '= ltrim(' || fieldname || ',''.'') where substr(' || fieldname
|| ',1,5) = ''.THE ''';
dbms_output.put_line (sqlst);
execute immediate sqlst;
end test;will update every row that satisfies the criteria in a single statement. If there are 10 rows that start with '.THE ' then it will update 10 rows.
Maybe you are looking for
-
Just upgraded to a G5-awesome. All calendars seem to have transferred & synced no problem- but today when I tried to search in events & to do's for an event ical came up with with no matches...even when I'm looking at an event with the same title I'm
-
Error received at a secure website
When I attempt to log into my banks secure online website I receive an error in No active sessions found. My bank tells me that I should alway allow cookies. What I have found is that when I go to show cookies, I don't even see the banks site in my c
-
Hi , Colud you please clearify the error "The system not able to read the WRITE BACK template.Please contact your system Administrator. for that, I folled this Document. http://rajeshthomas.blogspot.in/2012/08/writeback-analysis-in-obiee-11g-part-1.h
-
My membership renews June 11, 2014. I pay monthly, presently, but I want to pay annually, if it is cheaper. How do I proceed?
-
10053 - no trace file generated
Hi, no 10053 trace file is generated in the diag directory. sql_trace = true trace_enabled = true i set ALTER SESSION SET TRACEFILE_IDENTIFIER = 'TEST'; ALTER SESSION SET EVENTS='10053 trace name context forever, level 1'; but there is no trace file