'parameterising' sql statement - options?
hi - apologies for the cryptic title, I have a rather hefty reporting query, currently it runs in an acceptable time for a single 'id' at a time. however when I run it for multiple id's, the explain plan and running time grow exponentially, and it becomes 'unacceptable'.
don't shout, but I'm loathe to start rewriting the sql predicates again as it's took an age to get it producing the correct results for each id, at the minute it's in a very 'delicate' state, if that makes sense.
It's almost as if I want to wrap the statement in a for loop of id's, so it runs for just one id each time, but I don't want to move it to plsql if I can help it.
so I was just wondering if I have any options here? Is there some kind of sql construct I can use to have a big query run n times, 'mimic' a for loop, etc?
apologies if that's unclear, it's been a long day and I've given up caffeine, so am seriously flagging. :o)
oops, btw:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0
smon wrote:
so I was just wondering if I have any options here? Is there some kind of sql construct I can use to have a big query run n times, 'mimic' a for loop, etc?Yep - you can code such a construct. Basic approach in {message:id=9667189}. But there are other methods too - like cartesian joins for example, where the cartesian table is your for-loop index (and these are joined with every row from the other table, thus putting every row from that thru the loop so to speak).
As for paramaterising SQL in general - that is usually done using a context name-value (and the SYS_CONTEXT() function to get to it).
Another method would be to wrap the SQL as a pipeline table function and use a PL/SQL for-loop to do the driving.
None of these methods however typically makes sense. Pretty much for dealing with exceptions and not the run-of-the-mill stuff. Issue of course is making an exception is just that - and dealing with the issues it usually causes.
Similar Messages
-
Hi All,
we have a problem with profile option "Initialization SQL Statement - Custom". we have set this at user level. after some time, we have cleared the profile option value for this user.
But we can still see the generated trace files are getting updated. we did checked this trc files from path returned from below query.
select name, value
from v$parameter
where name like 'user_dump_dest';
Please help us on how to resolve this issue. we are using Oracle Apps R 12.1.2 version.
Thanks in advance
RaghavaBefore logging out we suspect that he closed the browser instead of logout link.
What if you make the user logout, can you reproduce the issue then?
We have verified the profile options for this user and found that value is cleared for profile Initialization SQL Statement - Custom.
How do you know that the files were generated for this user and because of this profile option? Have you verified profile options for all users at all level?
Thanks,
Hussein -
HOW TO: Post a SQL statement tuning request - template posting
This post is not a question, but similar to Rob van Wijk's "When your query takes too long ..." post should help to improve the quality of the requests for SQL statement tuning here on OTN.
On the OTN forum very often tuning requests about single SQL statements are posted, but the information provided is rather limited, and therefore it's not that simple to provide a meaningful advice. Instead of writing the same requests for additional information over and over again I thought I put together a post that describes how a "useful" post for such a request should look like and what information it should cover.
I've also prepared very detailed step-by-step instructions how to obtain that information on my blog, which can be used to easily gather the required information. It also covers again the details how to post the information properly here, in particular how to use the \ tag to preserve formatting and get a fixed font output:
http://oracle-randolf.blogspot.com/2009/02/basic-sql-statement-performance.html
So again: This post here describes how a "useful" post should look like and what information it ideally covers. The blog post explains in detail how to obtain that information.
In the future, rather than requesting the same additional information and explaining how to obtain it, I'll simply refer to this HOW TO post and the corresponding blog post which describes in detail how to get that information.
*Very important:*
Use the \ tag to enclose any output that should have its formatting preserved as shown below.
So if you want to use fixed font formatting that preserves the spaces etc., do the following:
\ This preserves formatting
\And it will look like this:
This preserves formatting
. . .Your post should cover the following information:
1. The SQL and a short description of its purpose
2. The version of your database with 4-digits (e.g. 10.2.0.4)
3. Optimizer related parameters
4. The TIMING and AUTOTRACE output
5. The EXPLAIN PLAN output
6. The TKPROF output snippet that corresponds to your statement
7. If you're on 10g or later, the DBMS_XPLAN.DISPLAY_CURSOR output
The above mentioned blog post describes in detail how to obtain that information.
Your post should have a meaningful subject, e.g. "SQL statement tuning request", and the message body should look similar to the following:
*-- Start of template body --*
The following SQL statement has been identified to perform poorly. It currently takes up to 10 seconds to execute, but it's supposed to take a second at most.
This is the statement:
select
from
t_demo
where
type = 'VIEW'
order by
id;It should return data from a table in a specific order.
The version of the database is 11.1.0.7.
These are the parameters relevant to the optimizer:
SQL>
SQL> show parameter optimizer
NAME TYPE VALUE
optimizer_capture_sql_plan_baselines boolean FALSE
optimizer_dynamic_sampling integer 2
optimizer_features_enable string 11.1.0.7
optimizer_index_caching integer 0
optimizer_index_cost_adj integer 100
optimizer_mode string ALL_ROWS
optimizer_secure_view_merging boolean TRUE
optimizer_use_invisible_indexes boolean FALSE
optimizer_use_pending_statistics boolean FALSE
optimizer_use_sql_plan_baselines boolean TRUE
SQL>
SQL> show parameter db_file_multi
NAME TYPE VALUE
db_file_multiblock_read_count integer 8
SQL>
SQL> show parameter db_block_size
NAME TYPE VALUE
db_block_size integer 8192
SQL>
SQL> show parameter cursor_sharing
NAME TYPE VALUE
cursor_sharing string EXACT
SQL>
SQL> column sname format a20
SQL> column pname format a20
SQL> column pval2 format a20
SQL>
SQL> select
2 sname
3 , pname
4 , pval1
5 , pval2
6 from
7 sys.aux_stats$;
SNAME PNAME PVAL1 PVAL2
SYSSTATS_INFO STATUS COMPLETED
SYSSTATS_INFO DSTART 01-30-2009 16:25
SYSSTATS_INFO DSTOP 01-30-2009 16:25
SYSSTATS_INFO FLAGS 0
SYSSTATS_MAIN CPUSPEEDNW 494,397
SYSSTATS_MAIN IOSEEKTIM 10
SYSSTATS_MAIN IOTFRSPEED 4096
SYSSTATS_MAIN SREADTIM
SYSSTATS_MAIN MREADTIM
SYSSTATS_MAIN CPUSPEED
SYSSTATS_MAIN MBRC
SYSSTATS_MAIN MAXTHR
SYSSTATS_MAIN SLAVETHR
13 rows selected.Here is the output of EXPLAIN PLAN:
SQL> explain plan for
2 -- put your statement here
3 select
4 *
5 from
6 t_demo
7 where
8 type = 'VIEW'
9 order by
10 id;
Explained.
Elapsed: 00:00:00.01
SQL>
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 1390505571
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 60 | 0 (0)| 00:00:01 |
| 1 | TABLE ACCESS BY INDEX ROWID| T_DEMO | 1 | 60 | 0 (0)| 00:00:01 |
|* 2 | INDEX RANGE SCAN | IDX_DEMO | 1 | | 0 (0)| 00:00:01 |
Predicate Information (identified by operation id):
2 - access("TYPE"='VIEW')
14 rows selected.Here is the output of SQL*Plus AUTOTRACE including the TIMING information:
SQL> rem Set the ARRAYSIZE according to your application
SQL> set autotrace traceonly arraysize 100
SQL> select
2 *
3 from
4 t_demo
5 where
6 type = 'VIEW'
7 order by
8 id;
149938 rows selected.
Elapsed: 00:00:02.21
Execution Plan
Plan hash value: 1390505571
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 60 | 0 (0)| 00:00:01 |
| 1 | TABLE ACCESS BY INDEX ROWID| T_DEMO | 1 | 60 | 0 (0)| 00:00:01 |
|* 2 | INDEX RANGE SCAN | IDX_DEMO | 1 | | 0 (0)| 00:00:01 |
Predicate Information (identified by operation id):
2 - access("TYPE"='VIEW')
Statistics
0 recursive calls
0 db block gets
149101 consistent gets
800 physical reads
196 redo size
1077830 bytes sent via SQL*Net to client
16905 bytes received via SQL*Net from client
1501 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
149938 rows processed
SQL>
SQL> disconnect
Disconnected from Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing optionsThe TKPROF output for this statement looks like the following:
TKPROF: Release 11.1.0.7.0 - Production on Mo Feb 23 10:23:08 2009
Copyright (c) 1982, 2007, Oracle. All rights reserved.
Trace file: orcl11_ora_3376_mytrace1.trc
Sort options: default
count = number of times OCI procedure was executed
cpu = cpu time in seconds executing
elapsed = elapsed time in seconds executing
disk = number of physical reads of buffers from disk
query = number of buffers gotten for consistent read
current = number of buffers gotten in current mode (usually for update)
rows = number of rows processed by the fetch or execute call
select
from
t_demo
where
type = 'VIEW'
order by
id
call count cpu elapsed disk query current rows
Parse 1 0.00 0.00 0 0 0 0
Execute 1 0.00 0.00 0 0 0 0
Fetch 1501 0.53 1.36 800 149101 0 149938
total 1503 0.53 1.36 800 149101 0 149938
Misses in library cache during parse: 0
Optimizer mode: ALL_ROWS
Parsing user id: 88
Rows Row Source Operation
149938 TABLE ACCESS BY INDEX ROWID T_DEMO (cr=149101 pr=800 pw=0 time=60042 us cost=0 size=60 card=1)
149938 INDEX RANGE SCAN IDX_DEMO (cr=1881 pr=1 pw=0 time=0 us cost=0 size=0 card=1)(object id 74895)
Elapsed times include waiting on following events:
Event waited on Times Max. Wait Total Waited
---------------------------------------- Waited ---------- ------------
SQL*Net message to client 1501 0.00 0.00
db file sequential read 800 0.05 0.80
SQL*Net message from client 1501 0.00 0.69
********************************************************************************The DBMS_XPLAN.DISPLAY_CURSOR output:
SQL> -- put your statement here
SQL> -- use the GATHER_PLAN_STATISTICS hint
SQL> -- if you're not using STATISTICS_LEVEL = ALL
SQL> select /*+ gather_plan_statistics */
2 *
3 from
4 t_demo
5 where
6 type = 'VIEW'
7 order by
8 id;
149938 rows selected.
Elapsed: 00:00:02.21
SQL>
SQL> select * from table(dbms_xplan.display_cursor(null, null, 'ALLSTATS LAST'));
PLAN_TABLE_OUTPUT
SQL_ID d4k5acu783vu8, child number 0
select /*+ gather_plan_statistics */ * from t_demo
where type = 'VIEW' order by id
Plan hash value: 1390505571
| Id | Operation | Name | Starts | E-Rows | A-Rows | A-Time | Buffers | Reads |
| 0 | SELECT STATEMENT | | 1 | | 149K|00:00:00.02 | 149K| 1183 |
| 1 | TABLE ACCESS BY INDEX ROWID| T_DEMO | 1 | 1 | 149K|00:00:00.02 | 149K| 1183 |
|* 2 | INDEX RANGE SCAN | IDX_DEMO | 1 | 1 | 149K|00:00:00.02 | 1880 | 383 |
Predicate Information (identified by operation id):
2 - access("TYPE"='VIEW')
20 rows selected.I'm looking forward for suggestions how to improve the performance of this statement.
*-- End of template body --*
I'm sure that if you follow these instructions and obtain the information described, post them using a proper formatting (don't forget about the \ tag) you'll receive meaningful advice very soon.
So, just to make sure you didn't miss this point:Use proper formatting!
If you think I missed something important in this sample post let me know so that I can improve it.
Regards,
Randolf
Oracle related stuff blog:
http://oracle-randolf.blogspot.com/
SQLTools++ for Oracle (Open source Oracle GUI for Windows):
http://www.sqltools-plusplus.org:7676/
http://sourceforge.net/projects/sqlt-pp/Alex Nuijten wrote:
...you missed the proper formatting of the Autotrace section ;-)Alex,
can't reproduce, does it still look unformatted? Or are you simply kidding? :-)
Randolf
PS: Just noticed that it actually sometimes doesn't show the proper formatting although the code tags are there. Changing to the \ tag helped in this case, but it seems to be odd.
Edited by: Randolf Geist on Feb 23, 2009 11:28 AM
Odd behaviour of forum software -
Produce report NOT based on a single sql statement
I want to produce a tabular report based on a series of sql statments. Specifically, a report of managers that wil include counts of employees that are in other tables using differing criterias.
Name Count Count
using using
criteria 1 criteria 2
Manager1 35 242
I would expect to write an anonymous pl/sql block with a driving cursor determining the managers to report on. Within that cursor, I would execute a number of other queries to derive the count for each of the two columns.
I have tried creating a report region based on a sql statement, but that requires a single sql statement. I also tried creating a report region based on plsql, but it required an into statement of defined items. This option looks like it can provide multiple rows, but since it selected 'INTO' named fields, it only creates a report with the last row of data.
I must be missing something. Any suggestions are greatly appreciated!!!If you want a wizard to create the form and report for you then yes you need to have a table. One thing that you can do is define a view that contains the data you need and define an Instead Of trigger on that view so the automatic fetch and dml will work but you can have the data stored into the different objects. basically the view and the trigger work as a router/dispatcher for the data.
*edit*
I should also add that you can write a pl/sql package which does the fetch and the dml operations with the form items as input. This is the solution I would typically use for any form that was not a simple CRUD form for a table. One thing to note is for the fetch I prefer to use out parameters for the form items so it requires the developer to map the item to the param in the app so it will show up when you are searching through the app. I highly discourage hiding item references inside of packaged code.
Good Luck!
Tyson
Message was edited by: TysonJouglet -
SQLEXEC not able to filter extract on sql statement or function call.
hi all,
i'm trying to do some basic extract filtering using a stored function and am not having much success.
i started off using a procedure call but have been unsuccessful getting that working, i've simplified
it to use a sql statement calling a function for a value to filter on, but cannot even get that to work.
i've read through the documentation and i cannot figure out what is going wrong.
any help would be much appreciated.
thx,
daniel
function code is very simple, just trying to get something working.
FUNCTION f_lookup_offer_id(v_offer_id IN offer.offer_id%TYPE)
RETURN company.name%TYPE IS
lv_company_name company.name%TYPE;
BEGIN
SELECT c.name
INTO lv_company_name
FROM orders a, offer b, company c
WHERE a.offer_id = b.offer_id
AND b.company_id = c.company_id
AND a.order_id = v_order_id;
RETURN lv_company_name;
END f_lookup_offer_id ;
Oracle GoldenGate Command Interpreter for Oracle
Version 11.1.1.0.0 Build 078
Solaris, sparc, 64bit (optimized), Oracle 10 on Jul 28 2010 13:26:39
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
EXTRACT EATUOP1
INCLUDE ./dirprm/GGS_LOGIN.inc
EXTTRAIL ./dirdat/up
DISCARDFILE ./dirout/eatuop1.dsc, append , MEGABYTES 50
DISCARDROLLOVER ON SUNDAY AT 06:00
-- Database and DDL Options
-- Added to avoid errors when setting unused columns
DBOPTIONS ALLOWUNUSEDCOLUMN
-- Get full row for deletes
NOCOMPRESSDELETES
-- Get updates before
GETUPDATEBEFORES
-- If commit SCN that is not greater than the highest SCN already processed error
THREADOPTIONS MAXCOMMITPROPAGATIONDELAY 15000 IOLATENCY 6000
-- Retains original timestamp. Currently using GMT
NOTCPSOURCETIMER
--TABLE DEFS
TABLE master.OFFER,
SQLEXEC ( ID ck_offer,
QUERY " select master.f_lookup_offer_id(:off_id) is_company from dual ",
PARAMS (off_id = offer_id),
BEFOREFILTER),
FILTER (@GETVAL (ck_offer.is_company = "Google, Inc."));
does not give any errors, but also does not capture any data, it's filtering everything out and trail files are empty, minus a header.
thoughts or help?
2012-04-04 22:17:36 INFO OGG-00993 Oracle GoldenGate Capture for Oracle, eatuop1.prm: EXTRACT EATUOP1 started.
2012-04-04 22:17:36 INFO OGG-01055 Oracle GoldenGate Capture for Oracle, eatuop1.prm: Recovery initialization completed for target file ./dirdat/up000022, at RBA 978.
2012-04-04 22:17:36 INFO OGG-01478 Oracle GoldenGate Capture for Oracle, eatuop1.prm: Output file ./dirdat/up is using format RELEASE 10.4/11.1.
2012-04-04 22:17:36 INFO OGG-01026 Oracle GoldenGate Capture for Oracle, eatuop1.prm: Rolling over remote file ./dirdat/up000022.
2012-04-04 22:17:36 INFO OGG-01053 Oracle GoldenGate Capture for Oracle, eatuop1.prm: Recovery completed for target file ./dirdat/up000023, at RBA 978.
2012-04-04 22:17:36 INFO OGG-01057 Oracle GoldenGate Capture for Oracle, eatuop1.prm: Recovery completed for all targets.
2012-04-04 22:17:36 INFO OGG-01517 Oracle GoldenGate Capture for Oracle, eatuop1.prm: Position of first record processed Sequence 13469, RBA 21894160, SCN 1789.722275534, Apr 4, 2012 10:12:40 PM.
-rw-rw-rw- 1 svc_ggs 502 978 Apr 4 22:17 up000023got it working, this seems to be about as simple as i could formulate it. thanks for pointing me in the right direction.
TABLE GGS_TEST_EXT, &
SQLEXEC ( ID co_count, &
QUERY " select f_lookup_company_name(:P1) x from dual ", &
PARAMS ( P1 = company_id), BEFOREFILTER), &
FILTER ( @GETVAL (co_count.x = 0) );
then i have a function that returns 1 or 0, depending on the company id passed in.
thx,
daniel -
Possible to do "grant" sql statement in Native SQL?
We have a need to do a grant of access from one of our systems out for various applications. In order for this to work we need to run a grant access command on the table and are trying to put a wrapper around this so we can use an abap. Below is the code I am unit testing. Two questions. First, can a grant be done via native SQL in abap? Second, if it can be done, what is the error with the logic where I am trying to put in the table name via a parameter.
REPORT ZLJTEST2.
tables dd02l.
DATA scarr_carrid TYPE dd02l-tabname.
SELECT-OPTIONS s_carrid for dd02l-tabname no intervals.
DATA s_carrid_wa LIKE LINE OF s_carrid.
DATA name TYPE c LENGTH 20.
TRY.
EXEC SQL.
CREATE FUNCTION selfunc( input CHAR(20) )
RETURNING char(20);
DEFINE output char(20);
set schema sapr3;
grant select on table input to group infouser;
RETURN output;
END FUNCTION;
ENDEXEC.
LOOP AT s_carrid INTO s_carrid_wa
WHERE sign = 'I' AND option = 'EQ'.
TRY.
EXEC SQL.
EXECUTE PROCEDURE selfunc( IN :s_carrid_wa-low,
OUT :name )
ENDEXEC.
WRITE: / s_carrid_wa-low, name.
CATCH cx_sy_native_sql_error.
MESSAGE `Error in procedure execution` TYPE 'I'.
ENDTRY.
ENDLOOP.
EXEC SQL.
DROP FUNCTION selfunc;
ENDEXEC.
CATCH cx_sy_native_sql_error.
MESSAGE `Error in procedure handling` TYPE 'I'.
ENDTRY.Hi,
Yes it is posible.
I made one program like you want. But it need very long code.
Here I explain the idea:
1. Create Screen with input TEXT EDIT CONTROL.
This is for input SQL Statement.
2. Get SQL Statement from Text Edit Control using method <b>get_text_as_r3table</b>.
3. Now we need to separate SQL Statement into different table.
We Separate SELECT, FROM, WHERE, GROUP, HAVING, ORDER, etc.
4. We need dynamic internal table to store the data.
5. Select the data according SQL statement.
SELECT (IT_SELECT)
into corresponding fields of table <dyn_table>
FROM (IT_FROM)
WHERE (IT_WHERE)
GROUP BY (IT_GROUP)
HAVING (IT_HAVING)
ORDER BY (IT_ORDER).
6. Display our data using ALV GRID
Hopefully it will help you.
Regards, -
How to examine the generated SQL statement in Receiver JDBC Adapter
I have been searching this forum how to display te generated sql statement (by the jdbc receiver adapter).
The only suggestion is to use RWB, but I was unable to find any details about how to do so.
Any help is appreciatedHi,
To add, u can see the SQL Statements in Audit log of RWB.
Select Message Monitoring-> Adapter Engine. choose ur entry and click on Details option button, u can see the SQL Statements in Audit Log.
Regards,
Sudharshan
Message was edited by:
Sudharshan Aravamudan -
Hello,
I would like to use integer array( say..int count[] = new int[3];) on my sql statement to retrieve some values. Is there a way to use int array variable in sql statement?. If yes, how should I approach doing that?.
Thank You in Advance.
Regards,
Pinal.I'm going to be honest, I'm not so sure there is such a thing in standard SQL syntax so it would depend upon the database you were using as to whether this option was available as part of the SQL language.
My suggestion would be to cheat, naughty I know:String arrayString = "";
for (int i = 0; i < arrayInt.size(); i++) {
arrayString += "**" + arrayInt;
arrayString = arrayString.substring(2, arrayString.length());Then just parse arrayString in to an SQL VARCHAR or TEXT field.
Obviously when you return it just use StringTokenizer to split the string up using your deliminator (in this case **) and then convert the values back into an int array.
I'm not sure how efficient that code would be but it should do the job. -
Using sql function in xml sql statement
Hello,
I have following statement:
select field1, field2,....,field10 from table( cast (get_mhdata(:1,:2) as mhdata))
where mhdata is an oracle type with 10 fields.
It works good, but I don't know how can I use this statement in xml sql statement.
Please, can you tell me if it is really possible.
Thanks in regards.Hi
You cant pass the parameters if you are executing writing this select function from the communication channel.
You have 3 options:
1) Use a stored procedure and execute from the communication channel
2) Use a stored procedure and execute via message mapping in the IR - here you can pass parameters
3) Same as above but call the query via SQL select - you can also pass parameters.
sincerely,
--NM -
Selection Screen Parameters in SQL statements
Very new ABAP programmer here, so sorry if this is a really dumb question.
I'm trying to use my selection screen parameters to limit what is pulled in by my SQL statement (which seems to me to be a very logical thing to do). But I'm having a problem, that when no values are entered in the parameters, no data is returned in the table instead of all the data being returned.
Here is the code I have now:
SELECT cname1 akostl aorgeh asname apernr bbegda bendda bstatu
bconfl bmedcf breasn breman b~rqday
INTO CORRESPONDING FIELDS OF TABLE it_record
FROM ( ( pa0001 AS a
INNER JOIN pa0672 AS b ON bpernr = apernr )
INNER JOIN t500p AS c ON cpersa = awerks )
WHERE b~reman in so_reman
AND a~kostl in so_kostl
AND a~orgeh = p_orgeh
AND b~begda = p_begda
AND b~statu = p_statu
AND b~confl = p_confl
AND b~medcf = p_medcf
AND b~reasn = p_reasn
AND b~rqday = p_rqday
AND c~name1 = p_name1.
Can anyone tell me what I'd need to do to make it return properly?When you use parameters and no value is entered, it is treated as initial value. and the select statement looks for the initial values for those fields in the tabl;e...
you can make the parameters mandatory..then the user would be forced to enter something....
also you could do the following..
instead of parameters, use select-options with the addition no intervals and no extension, then practically it looks like a parameter but internally it is a select-option...
and in the select statement, give conditions like....field1 in <s_option name>....in this case if the user is not entering a value ...it is treated as *...
Thnaks & Regards,
Renjith -
SQL Statements in ABAP and meaning
Hello Friends,
Please, can anybody provide me a documentation on the different ABAP SQL statements and there usage/meanings.
Thanks,
Shreekanthi,
goto abapdocu->abap Database access->open Sql you will get examples.
for documnetation got se38->specify the command and press F1.
SELECT:
Put the curson on that word and press F1 . You can see the whole documentation for select statements.
SELECT result
FROM source
INTO|APPENDING target
[[FOR ALL ENTRIES IN itab] WHERE sql_cond]
Effect
SELECT is an Open-SQL-statement for reading data from one or several database tables into data objects.
The select statement reads a result set (whose structure is determined in result ) from the database tables specified in source, and assigns the data from the result set to the data objects specified in target. You can restrict the result set using the WHERE addition. The addition GROUP BY compresses several database rows into a single row of the result set. The addition HAVING restricts the compressed rows. The addition ORDER BY sorts the result set.
The data objects specified in target must match the result set result. This means that the result set is either assigned to the data objects in one step, or by row, or by packets of rows. In the second and third case, the SELECT statement opens a loop, which which must be closed using ENDSELECT. For every loop pass, the SELECT-statement assigns a row or a packet of rows to the data objects specified in target. If the last row was assigned or if the result set is empty, then SELECT branches to ENDSELECT . A database cursor is opened implicitly to process a SELECT-loop, and is closed again when the loop is ended. You can end the loop using the statements from section leave loops.
Up to the INTO resp. APPENDING addition, the entries in the SELECTstatement define which data should be read by the database in which form. This requirement is translated in the database interface for the database system´s programming interface and is then passed to the database system. The data are read in packets by the database and are transported to the application server by the database server. On the application server, the data are transferred to the ABAP program´s data objects in accordance with the data specified in the INTO and APPENDING additions.
System Fields
The SELECT statement sets the values of the system fields sy-subrc and sy-dbcnt.
sy-subrc Relevance
0 The SELECT statement sets sy-subrc to 0 for every pass by value to an ABAP data object. The ENDSELECT statement sets sy-subrc to 0 if at least one row was transferred in the SELECT loop.
4 The SELECT statement sets sy-subrc to 4 if the result set is empty, that is, if no data was found in the database.
8 The SELECT statement sets sy-subrc to 8 if the FOR UPDATE addition is used in result, without the primary key being specified fully after WHERE.
After every value that is transferred to an ABAP data object, the SELECT statement sets sy-dbcnt to the number of rows that were transferred. If the result set is empty, sy-dbcnt is set to 0.
Notes
Outside classes, you do not need to specify the target area with INTO or APPENDING if a single database table or a single view is specified statically after FROM, and a table work area dbtab was declared with the TABLES statement for the corresponding database table or view. In this case, the system supplements the SELECT-statement implicitly with the addition INTO dbtab.
Although the WHERE-condition is optional, you should always specify it for performance reasons, and the result set should not be restricted on the application server.
SELECT-loops can be nested. For performance reasons, you should check whether a join or a sub-query would be more effective.
Within a SELECT-loop you cannot execute any statements that lead to a database commit and consequently cause the corresponding database cursor to close.
SELECT - result
Syntax
... lines columns ... .
Effect The data in result defines whether the resulting set consists of multiple rows (table-like structure) or a single row ( flat structure). It specifies the columns to be read and defines their names in the resulting set. Note that column names from the database table can be changed. For single columns, aggregate expressions can be used to specify aggregates. Identical rows in the resulting set can be excluded, and individual rows can be protected from parallel changes by another program.
The data in result consists of data for the rows lines and for the columns columns.
SELECT - lines
Syntax
... { SINGLE }
| { { } } ... .
Alternatives:
1. ... SINGLE
2. ... { }
Effect
The data in lines specifies that the resulting set has either multiple lines or a single line.
Alternative 1
... SINGLE
Effect
If SINGLE is specified, the resulting set has a single line. If the remaining additions to the SELECT command select more than one line from the database, the first line that is found is entered into the resulting set. The data objects specified after INTO may not be internal tables, and the APPENDING addition may not be used.
An exclusive lock can be set for this line using the FOR UPDATE addition when a single line is being read with SINGLE. The SELECT command is used in this case only if all primary key fields in logical expressions linked by AND are checked to make sure they are the same in the WHERE condition. Otherwise, the resulting set is empty and sy-subrc is set to 8. If the lock causes a deadlock, an exception occurs. If the FOR UPDATE addition is used, the SELECT command circumvents SAP buffering.
Note
When SINGLE is being specified, the lines to be read should be clearly specified in the WHERE condition, for the sake of efficiency. When the data is read from a database table, the system does this by specifying comparison values for the primary key.
Alternative 2
Effect
If SINGLE is not specified and if columns does not contain only aggregate expressions, the resulting set has multiple lines. All database lines that are selected by the remaining additions of the SELECT command are included in the resulting list. If the ORDER BY addition is not used, the order of the lines in the resulting list is not defined and, if the same SELECT command is executed multiple times, the order may be different each time. A data object specified after INTO can be an internal table and the APPENDING addition can be used. If no internal table is specified after INTO or APPENDING, the SELECT command triggers a loop that has to be closed using ENDSELECT.
If multiple lines are read without SINGLE, the DISTINCT addition can be used to exclude duplicate lines from the resulting list. If DISTINCT is used, the SELECT command circumvents SAP buffering. DISTINCT cannot be used in the following situations:
If a column specified in columns has the type STRING, RAWSTRING, LCHAR or LRAW
If the system tries to access pool or cluster tables and single columns are specified in columns.
Note
When specifying DISTINCT, note that you have to carry out sort operations in the database system for this.
SELECT - columns
Syntax
| { {col1|aggregate( col1 )}
{col2|aggregate( col2 )} ... }
| (column_syntax) ... .
Alternatives:
1. ... *
2. ... {col1|aggregate( col1 )}
{col2|aggregate( col2 )} ...
3. ... (column_syntax)
Effect
The input in columns determines which columns are used to build the resulting set.
Alternative 1
Effect
If * is specified, the resulting set is built based on all columns in the database tables or views specified after FROM, in the order given there. The columns in the resulting set take on the name and data type from the database tables or views. Only one data object can be specified after INTO.
Note
If multiple database tables are specified after FROM, you cannot prevent multiple columns from getting the same name when you specify *.
Alternative 2
... {col1|aggregate( col1 )}
{col2|aggregate( col2 )} ...
Effect
A list of column labels col1 col2 ... is specified in order to build the resulting list from individual columns. An individual column can be specified directly or as an argument of an aggregate function aggregate. The order in which the column labels are specified is up to you and defines the order of the columns in the resulting list. Only if a column of the type LCHAR or LRAW is listed does the corresponding length field also have to be specified directly before it. An individual column can be specified multiple times.
The addition AS can be used to define an alternative column name a1 a2 ... with a maximum of fourteen digits in the resulting set for every column label col1 col2 .... The system uses the alternative column name in the additions INTO|APPENDING CORRESPONDING FIELDS and ORDER BY. .
http://help.sap.com/saphelp_nw04/helpdata/en/62/10a423384746e8bf5f15ccdd36e8b1/content.htm -
TestStand Open SQL Statement does not support SQL's ORDER BY clause???
TestStand 1.0.3
Windows 2000 SP1
SQL Server 2000 Personal
You've got to be kidding me...
It appears that the built-in TestStand Open SQL Step does NOT support the
"ORDER BY" clause in the SELECT statement, even though the documentation
says it does. Is this true?
I have an Open SQL Statement query:
"SELECT * FROM [MyTable] WHERE ([Batch ID]=1234)"
it works fine, returning a correct record count 120 records. If I change
the Open SQL Statement query simply by adding an ORDER BY clause, such as:
"SELECT * FROM [MyTable] WHERE ([Batch ID]=1234) ORDER BY [MyField] ASC"
it returns a record count of zero. I know that "MyField" exists in the
MyTable table and contains valid data. The
second query works fine in SQL
Server Enterprise Manager.
Am I missing something? Is it true that the TestStand Open SQL Step does
NOT support the "ORDER BY" clause? If not, what &#$!ing good is it and why
does the manual state it is supported? Is there any other way using just
the TestStand steps to order a database recordset on one or more fields?
Any help would be appreciated.
Grrrrr....
Bob Rafuse
Etec Inc.> Bob -
> The database step types do not do anything special to the SQL command
> that you give it. The step just passes the command to the ADO
> provider. I tried a simple query using the step types with the
> following command,
>
> "SELECT UUT_RESULT.* FROM UUT_RESULT WHERE ([UUT_SERIAL_NUMBER] =
> 12345) ORDER BY [EXECUTION_TIME] ASC"
>
> and this return the expected results and the record count parameter
> was as expected. I tried this on TS 1.0.2 and TS 2.0 with MS Access
> 2000 and MS SQL Server 7.0. I do not have MS SQL Server 2000 at this
> time.
>
> It would be surprised if the step types are messing something up.
I've been doing some experimenting over the past couple of days. Simple,
one-table queries seem to handle the ORDER BY clause fine. Th
ings seem to
get messed up when I try multi-table queries with ORDER BY clause with the
TestStand database steps. I get no errors but the returned record counts
are always 0 with the ORDER BY and positive without the ORDER BY. The exact
same queries work fine in Visual Basic/ADO and the SQL Server Query
Analyzer.
> Questions:
> 1. Have you verified whether the data is actually returned even though
> the record count is zero?
Hmmm... yes data IS getting returned (at least on the two instances I just
checked), but the record count is always zero. I was not proceeding with
processing if the record count was 0.
Still... I don't know how to loop through the recordset without knowing how
many records there are an not eventually generate an error by passing EOF.
Is there another way using the TestStand database steps to determine a) the
number of records in the recordset or b) when I'm at EOF?
> 2. Are you using any advanced options on the Opend SQL Statement step
> type, specifically
the cursor type set to forward only? Forward only
> cursors do not allow for record counts.
Everything on the Advanced tab of the Open SQL Statement step is set to "Use
Default".
Bob. -
How to view the SQL statement generated during execution of the BW Query?
Dear Experts,
I am trying to retrieve data in a SAP BW Query from a Non-SAP system.
I think if I am able to see the complete SQL statement that was generated when I executed the BW Query, I may be able to use it to retrieve the data.
Do you know how and where I can see the SQL statement of a BW Query's SQL statement?
I tried RSRT options to execute the Query but still could not find the SQL statement.
Thanks in advance.
Regards,
Shunhui.hi
goto rsrt
give your query name
select execute + debug option
in the debug option under data manager check the check box "display SQL/BIA query
selcet continue
you can see the sql statement
thanq -
Sender JDBC adapter : Update SQL Statement : stored procedure
Hi,
Can we use a stored procedure in the sender jdbc adapter in 'Update SQL Statement'.
The problem i am facing is like, we are selecting data from two tables in 'SQL statement for query' and then in 'Update SQL Statement' , we need to delete that data from these two tables.
Please let me know if it is possible.
Thanks,
Rohityou can use a Stored procedure in the
Query SQL Statement
You have the following options:
· Specify a valid SQL SELECT statement to select the data to be sent from the specified database.
· Specify an SQL EXECUTE statement to execute a stored procedure, which contains exactly one SELECT statement.
The expression must correspond to the SQL variant supported by the relevant JDBC driver. It can also contain table JOINs.
so have your whole select and update as part of this single Stored procedure -
The maximum size of an SQL statement has been exceeded.
In ST22, abap dump shows that one of the possible reason was "The maximum size of an SQL statement has been exceeded."
How can I know what's the maximum size and how to compute that size had been reached?
Is this shown anywhere in the log?1. decalre temp_key as a table.
2. use this package size option ....this gets the data in bite-sized chunks
SELECT MATKL MATNR MEINS
INTO corresponding fields of table TEMP_KEY package size 1000
FROM MARA
WHERE MATNR IN SO_MATNR.
loop at temp_key.
MOVE-CORRESPONDING TEMP_KEY TO ITAB_KEY1.
IF WS_PCHR SPACE.
CLEAR ITAB_CHAR.
CLEAR ITAB_KEY1-CHARACTER. REFRESH ITAB_KEY1-CHARACTER.
PERFORM GET_CHAR TABLES ITAB_CHAR ITAB_KEY1-CHARACTER
USING ITAB_KEY1-MATNR.
ENDIF.
APPEND ITAB_KEY1. CLEAR ITAB_KEY1.
endloop.
ENDSELECT.
Maybe you are looking for
-
I downloaded muse cc 2014. It worked fine for a while (couple of bugs though). Yesterday it would crash whenever it was launched. So i tried to uninstall and re-install. No Luck. Then noticed adobe cloud/adobe air windows were not starting up as per
-
my ipod touch 4g wont let me download apps and i already have an acount and have other apps what do i do?????
-
Files no longer show up on server
I have a PC server with all my files on it. I work on the files from the mac. It has to be set up this way for our RIP to access the files. My question is some files are no longer showing up on the mac. They are on the PC and when I delete and copy t
-
Exporting to Quicktime for older versions
Hello. I have a the latest version of QT and so when I export a video, it plays on my computer but not for folks running older Window versions. Is there a way I can export to a QT 6 clip without having to re-install the older version of QT therefore
-
Question about MX7 and Oracle 10GR2 RAC
Can someone tell me if it's possible to pass parameter names to and oracle function in MX7. I have a function that returns a refcursor that worked fine as a simply function now it's an overloaded function and I need to pass different parameter names