How to use Dynamic SQL in ABAP
If I have mara table and I have an selection screen where I have allowed user to select the fields of MARA,Now What I want is depending on his selection we should be able to execute the sql command.
E.g.
Tables: mara.
selection-screen
MATNR , ERSDA , ERNAM , MTART , MEINS.
NOW THE OUTPUT SHOULD BE ABLE TO DISPLAY ONLY THE SELECTED FIELD VALUE.
Hello Nandan,
Try the following code. It works.
tables: mara.
data: tablename type tabname,
fname type fieldname,
fieldnames type fieldname occurs 0.
field-symbols : <fs_tableline> type any,
<fs_fieldval> type any.
initialization.
tablename = 'MARA'.
assign (tablename) to <fs_tableline> .
fname = 'MATNR'.
append fname to fieldnames.
fname = 'MTART'.
append fname to fieldnames.
select (fieldnames)
from (tablename)
up to 20 rows
into corresponding fields of <fs_tableline>.
loop at fieldnames into fname.
assign component fname of structure <fs_tableline> to <fs_fieldval>.
write : <fs_fieldval>.
endloop.
new-line.
endselect.
The <b>tables</b> statement is very important. You should at least have the list of the tables which you expect the user to enter.
Please do get back if you have any doubts. If you think the question is answered, please reward the points to the useful answers and close the thread.
Regards,
Anand Mandalika.
Similar Messages
-
Can anybody please send me a small program on How to Use Dynamic SQL.
How to execute and run give details.
Thanks
nullYou can certainly use the INTO (and USING) clauses of EXECUTE IMMEDIATE to pass in and return data, i.e.
EXECUTE IMMEDIATE sqlStmt
USING variable1, variable2
INTO output1, output2The more complex the statement, however, the more appropriate DBMS_SQL is. DBMS_SQL also has the potential to allow you to use bind variables rather than reparsing the statement many times.
Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC -
How to use dynamic SQL in this case for best performance
I have the table with following columns
ID NUMBER,
DATA LONG,
TAG VARCHAR2(255)
Records in this table will be like following
1 this is an abstract ABSTRACT
1 this is author AUTHOR
1 100 PRICE
2 this is an abstract ABSTRACT
2 this is author AUTHOR
3 contract is this CONTRACT
Basically all the records with the same number constitute 1 record for another table. Tag in the above table indicates that what column it is and DATAwill have the actual data for that column. I need to populate the second table based an the above table but will not get the same number of TAGS all the time. I need to insert the values only for the columns provided in the TAG field. How will I accomplish this by dynamic sql. Do I create a loop and create two strings one with columns and one with values and then combine them and use execute immediate to insert into table? Is there an easier way to do this??
Please respond quickly.
Thanks
Bhawna
null> so which collection should i use to perform it..
so that performance is best......
Program to interfaces. That way, you can switch out implementations and test for yourself which performance is best in an actual production context. But first, write your program so that it works. Worry about refactoring for performance once your program is written and it works.
> plz send me the logic....
Give it a shot on your own first; we can help if you get stuck.
~ -
Hi experts, how to use open sql to read data from one " maintenance view"?
i want to use this part of data within report ,so how to use open sql statement to read data from one " maintenance view"?
Hi
You can't use OPEN SQl statements to fetch data from maintenance view
You have to use only Database views
see the different types of views and the difference
The followings are different types of views:
- Database View (SE11)
Database views are implement an inner join, that is, only records of the primary table (selected via the join operation) for which the corresponding records of the secondary tables also exist are fetched. Inconsistencies between primary and secondary table could, therefore, lead to a reduced selection set.
In database views, the join conditions can be formulated using equality relationships between any base fields. In the other types of view, they must be taken from existing foreign keys. That is, tables can only be collected in a maintenance or help view if they are linked to one another via foreign keys.
- Help View ( SE54)
Help views are used to output additional information when the online help system is called.
When the F4 button is pressed for a screen field, a check is first made on whether a matchcode is defined for this field. If this is not the case, the help view is displayed in which the check table of the field is the primary table. Thus, for each table no more than one help view can be created, that is, a table can only be primary table in at most one help view.
- Projection View
Projection views are used to suppress or mask certain fields in a table (projection), thus minimizing the number of interfaces. This means that only the data that is actually required is exchanged when the database is accessed.
A projection view can draw upon only one table. Selection conditions cannot be specified for projection views.
- Maintenance View ( SE54 )
Maintenance views enable a business-oriented approach to looking at data, while at the same time, making it possible to maintain the data involved. Data from several tables can be summarized in a maintenance view and maintained collectively via this view. That is, the data is entered via the view and then distributed to the underlying tables by the system.
Please have a look at below link. It will help you.
http://help.sap.com/saphelp_nw04/helpdata/en/cf/21ed06446011d189700000e8322d00/frameset.htm
for more detailed info look on:
http://www.sap-img.com/abap/what-is-the-different-types-and-usage-of-views.htm
https://www.sdn.sap.com/irj/sdn/wiki?path=/display/home/abap+dictionary&
Reward points for useful Answers
Regards
Anji -
Using dynamic sql in triggers with :OLD values
i need to record all deleted rows from an entire schema in a single table. for that matter i created a function that receives a table name and generate an insert command according to it's primary key columns. i call this function in the table triggers. in order to insert the old values before the delete i use :OLD with "execute immediate" as followed :
create or replace trigger trg_some_tbl_bd
before delete on some_tbl
for each row is
declare
v_sql varchar2(4000);
begin
v_sql := generate_insert_command('some_table');
execute immediate v_sql;
end;
the return value from "generate_insert_command" function is the string:
insert into deleted_table (table_name , date , pk1 , pk2) values
('some_table' , sysdate , :OLD.pk1 , :OLD.pk2)
the execute immediate command notice the :OLD and looks for bind variables.
i need to know i can i bypass that. i tried looking for escape characters but couldent find any...
i would appriciate any help , it's kynda urgent
Thanks !I don't believe this is going to work. Even if you could get around the fact that :old looks like a bind variable, the :old values are not visible to the dynamic SQL statement, they're like local variables in that respect.
If you wanted to pass old values in, those values would have to be passed in as bind variables, i.e.
EXECUTE IMMEDIATE v_sql USING :old.pk1, :old.pk2which defeats the purpose of using dynamic SQL.
Since you have to create a trigger for each table, I don't see why you would bother with dynamic SQL inside the trigger-- your table structure is fixed when the trigger is created. You could write dynamic SQL that generated the triggers in the first place, but the code inside the trigger should be dynamic.
As an aside, you realize that logging every audit record into a single table creates rather massive contention issues, right? And have you considered how painful it is to query this sort of table? Have you considered other options for maintaining history like Workspace Manager? Or at least separate history tables for each table?
Justin -
How to implement dynamic SQL (like dynamic SQL Method 4 in Pro*C), which
lets program accept or build dynamic SQL statements that contain an unknown
number of select-list items or placeholders?You don't need the Oracle specific stuff. You can use ResultSetMetadata to analyze what your SQL statement returned. (I assume that's what you mean with "number of select-list items"). Basically:Statement stmt = connection.createStatement();
boolean hasResult = stmt.execute(sql);
if (hasResult)
ResultSet rs = stmt.getResultSet();
ResultSetMetadata meta = rs. getMetaData();
for (int c=0; c < meta.getColumnCount(); c++)
System.out.println("Column: " + meta.getColumnName(c + 1); // column number starts at 1!
}You will not be able to check whether your statement contains parameters/placeholders (to be used with PreparedStatements) because the Oracle driver does not implement the necessary methods. -
How to use dynamic parameter when a report is created using Stored Procedures
Hi all,
any one have the idea of how to use dynamic parameter in crystal report XI R2
when report is created using Stored Procedure.
Regards
shashi kant chauhanHi
You can create an SQL command in Database Expert > Expand your datasource > Add command
Then enter the SQL query that will create the list of values to supply to the user
eg select field1,field2 from table
Then edit the parameter of the report. These will be the SP parameters adn can be seen in field explorer.
Change the parameter type to Dynamic
Under the word Value click on Click here to add item
Scroll down to your Command and select one of the values that you want to appear in the list
e.g field1
Then click on the Parameters field - this is essential to create the param
You can edit other options as required
That should do it for you.
I must say that i use CR 2008 connected to Oracle 10g SP, but i reckon this will work for SQL DB and CR XI as well
Best of luck -
Can we use Dynamic SQL in Oracle Reports ?
Hi ,
Can we use Dynamic SQL in Oracle Reports ?
If yes please give some examples .
Thanx
sriniI believe the built-in package SRW.Do_Sql is what you are looking for
Example from the document:
/* Suppose you want to create a "table of contents" by getting the
** first character of a columns value, and page number on which its
** field fires to print. Assume that you want to put the "table of
contents"
** into a table named SHIP. You could write the following construct:
DECLARE
PAGE_NO NUMBER;
PAGE_FOR INDEX NUMBER;
SORT_CHAR CHAR(1);
CMD_LINE CHAR(200);
BEGIN
SORT_CHAR := :SORT_NAME ;
IF :CALLED = Y THEN
SRW.GET_PAGE_NUM(PAGE_FOR_INDEX);
SRW.USER_EXIT(RWECOP PAGE_FOR_INDEX
P_START_PAGENO);
SRW.MESSAGE(2,TO_CHAR(:P_START_PAGENO));
END IF;
SRW.GET_PAGE_NUM(PAGE_NO);
CMD_LINE := INSERT INTO SHIP VALUES
(||SORT_CHAR||,||TO_CHAR(PAGE_NO)||);
SRW.MESSAGE(2,CMD_LINE);
SRW.DO_SQL(CMD_LINE);
COMMIT;
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
NULL;
WHEN SRW.DO_SQL_FAILURE THEN
SRW.MESSAGE(1,FAILED TO INSERT ROW INTO SHIP TABLE);
WHEN OTHERS THEN
COMMIT;
END; -
Getting error while using DYNAMIC SQL
Hi Team,
I am Oracle DBA. I have limited knowledge on PL/SQL. I used below PL/SQL code to drop 50 partitons from one of the table.
I used Dynamic SQL EXECUTE IMMEDIATE to drop partions. But error occured. If I commented EXECUTE IMMEDIATE, procedure executed successfully.
Please suggest me, where i did the mistake. Also please suggest for better code than my code. please find below code and error details.
SQL> ed
Wrote file afiedt.buf
1 DECLARE
2 CURSOR DROP_PARTITON IS select partition_name from user_tab_subpartitions where PARTITION_NAME<='ABCD_2011_04';
3 BEGIN
4 for curr IN DROP_PARTITON LOOP
5 DBMS_output.put_line(curr.partition_name);
6 execute immediate(Alter table Table_Name drop partition curr.partition_name);
7 end loop;
8* END;
SQL> /
execute immediate(Alter table BILLCHRG drop partition curr.partition_name);
ERROR at line 6:
ORA-06550: line 6, column 19:
PLS-00103: Encountered the symbol "ALTER" when expecting one of the following:
( - + case mod new not null others <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
<an alternatively-quoted string literal with character set specification>
<an alternative
SQL> ed
Wrote file afiedt.buf
1 DECLARE
2 CURSOR DROP_PARTITON IS select partition_name from user_tab_subpartitions where PARTITION_NAME<='ABCD_2011_04';
3 BEGIN
4 for curr IN DROP_PARTITON LOOP
5 DBMS_output.put_line(curr.partition_name);
6 --execute immediate(Alter table TABLE_NAME drop partition curr.partition_name);
7 end loop;
8* END;
SQL> /
ABCD_2009_06
ABCD_2009_06
ABCD_2009_06
BILLCHRG_2011_04
PL/SQL procedure successfully completed.PL/SQL code runs on the server, inside an Oracle process - thus PL/SQL code cannot dynamically write and display messages to the client. That server process is not connected to any keyboard, mouse or display.
DBMS_OUTPUT can be used. This is a PL/SQL buffer area in that server process that code can write lines of text too. When the server process informs the client that it has completed, the client can now request the contents of the DBMS_OUTPUT buffer and the client can display it on the client device.
This is what set serveroutput on in SQL*Plus does - tell the sqlplus client to request the DBMS_OUTPUT buffer after each Oracle server call made and to display the contents locally.
So to display the SQL command can be done using DBMS_OUTPUT. E.g.
declare
dropPart varchar2(32767);
begin
for c in (select...) loop
dropPart := 'alter table my_tab drop partition '||c.partition_name';
--// write the SQL command to DBMS_OUTPUT
DBMS_OUTPUT.put_line( dropPart );
--// execute the SQL using a begin..end block in order to catch error
begin
execute immediate dropPart;
DBMS_OUTPUT.put_line( 'command completed successfully' );
exception when OTHERS then
DBMS_OUTPUT.put_line( 'command failed with: '||SQLERRM(SQLCODE) );
end;
end loop;
end;So after this code block has been executed and partitions dropped, sqlplus will display the DBMS_OUTPUT generated by this code block. -
How to use messages in WebDynpro-ABAP
Hi,
How to use messages in WebDynpro-ABAP.
Does it has any class to manage messages like IWDMessageManager or we can just use standard SAP Message types.. like E,W,X,I,S..
I hope it have a message container to display messages.
Thank U for Ur time.
Cheers,
SamHi Sam,
U can hard code the message or u can use the Assistance class's text elements to store the messages.
1) Code to display hard coded message:
report message
CALL METHOD l_message_manager->report_attribute_error_message
EXPORTING
message_text = "Enter the correct Connection ID"
element = elem_flightinfo
attribute_name = 'CONNID'.
2) Code to display message from text element of assistance class:
lv_text = wd_assist->if_wd_component_assistance~get_text( key = '002' ).
report message
CALL METHOD l_message_manager->report_attribute_error_message
EXPORTING
message_text = lv_text
element = elem_flightinfo
attribute_name = 'CONNID'.
Where Message "Enter the Correct Connection ID" is stored in Text Element with key '002'
Hope this helps, -
How to use dynamic select query which queries from 3 different table.
Hi All,
I am new to Toplink, i would like to use a named query to select some of the columns from 3 different tables with dynamic where clause.
I have used the following lines. Please tell me how to get code for the dynamic where clause.
First try :
Vector objPersons = (Vector)session.executeQuery("findPersonByGlobalID",Person.class,vQueryArguments);
The above method is not returning the vector or collection.
Second Try:
ReadAllQuery query = new ReadAllQuery(Person.class);
query.useCollectionClass(LinkedList.class);
LinkedList person = (LinkedList) session.executeQuery(query);
The second try is returning the collection but, this fetches all the record from the table.
1. How to query for range of records?
2. How to query from multiple tables for some range. How to use dynamic range values ?
Please reply with your answers or some pointers would help.
Thanks and Regards,
Vijay.BHi,
Did you try using a SQLCall ? It might be able to satisfy you requirements .. :-
Employee employee = (Employee) session.executeSelectingCall(
new SQLCall("SELECT * FROM EMPLOYEE WHERE EMP_ID = 44")
);You can get more information here :-
http://www.oracle.com/technology/products/ias/toplink/doc/1013/MAIN/_html/qrybas004.htm
Regards,
Sandeep -
Delcare Cursor using Dynamic SQL using PL/SQL in Oracle 7.3.4
In Oracle 7.3.4, can I declare a cursor at run time using Dynamic SQL. From the sample code in this website, it seems that Oracle 8 support this function. Please help. Thanks a lot.
If I can do this on Oracle 7.3.4, could you give me some sample codes? Thanks.
Regards,
RaymondHi,
Try using the the following code where you can dynamically build the Valid Select stmt. and call that where ever you want.
declare
Type Cur_ref Is Ref Cursor;
C_ref Cur_ref;
V_Str Varchar2(100);
V_Name Varchar2(100);
Begin
V_Str := 'Select Ename from Scott.emp Where empno = 7369';
Open C_Ref for V_Str;
Fetch C_ref Into V_Name;
close C_Ref;
dbms_output.put_line(V_Name);
End;
regards
gaurav
null -
How to use dynamic list box in survey builder?
Hello,
Could someone give me a little bit of thread? How to use dynamic list box in survey builder?Hi Liu,
Dynamic combo boxes::A combo box is dynamic if it references a document property for which a value set is defined in the configuration (System Administration ® System Configuration ® Content Management ® Global Services ® Property Metadata ® Properties ® Parameter Allowed Values).
At runtime (when you open the creation form) the system reads these values from the configuration and displays them in the dropdown list.
If you link a combo box for which list entries already exist to a document property with a value set, the system asks whether you want to delete the list entries. it is recommend that you accept this suggestion and delete the list entries from the XML Forms Builder. Otherwise inconsistencies could arise between the entries in the XML Forms Builder and the value set in the configuration. This can cause errors when saving.
Also you may Refer the Link for Further help:
http://help.sap.com/saphelp_crm50/helpdata/en/29/c40d3d2a83752de10000000a114084/frameset.htm
http://help.sap.com/saphelp_crm50/helpdata/en/00/9e7f41969e1809e10000000a155106/frameset.htm
http://help.sap.com/saphelp_crm50/helpdata/en/a7/5a874174a8050de10000000a1550b0/frameset.htm
Hope it Answers your Queries..
Thanks and Regards,
RK. -
Does anyone know anything about Dynamic SQL not being available in Forms v. 6.0.8.11.3? I trying to use Dynamic SQL for the first time and am having some difficulty. When I try to put my SQL in a function and run it straight into the database through SQLPlus, it works fine, but when trying to compile the code in Forms Builder (in a library), I get compiler errors. Any help would be appreciated...
Thanks!
VanessaWhen I tried to compile the following code in Forms, the compiler error I got was Encountered the symbol "STMT_STR" when expecting one of the following: select. However, when I run it in SQLPlus, it creates the function without any errors.
FUNCTION my_func
return number
is
TYPE DiaryCurTyp IS REF CURSOR;
cur DiaryCurTyp;
stmt_str VARCHAR2(200);
dmonth NUMBER;
dday NUMBER;
BEGIN
stmt_str := 'SELECT dmonth, dday FROM p2_diary
WHERE dmonth = :1';
OPEN cur FOR stmt_str USING '12';
LOOP
FETCH cur INTO dmonth, dday;
EXIT WHEN cur%NOTFOUND;
-- <process data>
END LOOP;
CLOSE cur;
END; -
Are there any risks to use native sql in ABAP to access external DB
here is a requirement to use native sql in abap program to access external DB to load some data into sap. Are there any risks and effects which SAP not recommend ?
Can anybody show some official document to me because I want to know some risks and dangerous to report to my manager..thanks very much.hi Anversha s
thank you for your reply
I means what's the risk when to use native sql to access external DB..
can you show me some examples about open sql which is used to access external DB...
Now I am investigating the technique about the connection
between SAP (by abap program) and external DB...the supporter suggestion is to use native sql to access external DBs.but my manager is afraid of the risks when to use native sql,So I have to report the effective document (example: SAP official document) to explain to my manager.
thanks very much
Maybe you are looking for
-
"getting a javascript error while validating a JSP"
Hi folks, Someone help me out with this problem. I am getting a javascript validation error when I am trying to validate a JSP. if(eval("document.frmAdminSowAssignValues.chkSowEmployee"+i).checked) If I try to load a JSP page on a browser, it is givi
-
Can't find info. This question was solved. View Solution.
-
Home network and Externeal hard drives
I've recently set up a home network to allow me to share my files across my two iMac's. My older iMac I've setup with my external hard drives almost as a media center to allow my new Sonos speakers to use my itunes libary, all but one of these are fo
-
Data service (DB adapter) returns XML with missing collection's content
Hello. I am facing problem with DB adapter connected to MySQL database. When I use select from 1-2 tables (connected by master-detail relationship) adapter works fine. When I use more than 2 tables adapter returns only master table and empty detail c
-
Can anyone tell me which table contains the cost element groups and which cost elements are related to them