Dynamic select query with dynamic where condition
Hi all,
I want to use the dynamic select query with dynamic where condition. For that I used the below code but I am getting dump when using this code.
Please advice, if there is any other way to achieve this requirement.
Thanks,
Sanket Sethi
Code***************
PARAMETERS: p_tabnam TYPE tabname,
p_selfl1 TYPE edpline,
p_value TYPE edpline,
p_where1 TYPE edpline .
DATA: lt_where TYPE TABLE OF edpline,
lt_sel_list TYPE TABLE OF edpline,
l_wa_name TYPE string,
ls_where TYPE edpline,
l_having TYPE string,
dref TYPE REF TO data,
itab_type TYPE REF TO cl_abap_tabledescr,
struct_type TYPE REF TO cl_abap_structdescr,
elem_type TYPE REF TO cl_abap_elemdescr,
comp_tab TYPE cl_abap_structdescr=>component_table,
comp_fld TYPE cl_abap_structdescr=>component.
TYPES: f_count TYPE i.
FIELD-SYMBOLS : <lt_outtab> TYPE ANY TABLE,
* <ls_outtab> TYPE ANY,
<l_fld> TYPE ANY.
struct_type ?= cl_abap_typedescr=>describe_by_name( p_tabnam ).
elem_type ?= cl_abap_elemdescr=>describe_by_name( 'F_COUNT' ).
comp_tab = struct_type->get_components( ).
comp_fld-name = 'F_COUNT'.
comp_fld-type = elem_type.
APPEND comp_fld TO comp_tab.
struct_type = cl_abap_structdescr=>create( comp_tab ).
itab_type = cl_abap_tabledescr=>create( struct_type ).
l_wa_name = 'l_WA'.
CREATE DATA dref TYPE HANDLE itab_type.
ASSIGN dref->* TO <lt_outtab>.
*CREATE DATA dref TYPE HANDLE struct_type.
*ASSIGN dref->* TO <ls_outtab>.
* Creation of the selection fields
APPEND p_selfl1 TO lt_sel_list.
APPEND 'COUNT(*) AS F_COUNT' TO lt_sel_list.
** Creation of the "where" clause
*CONCATENATE p_selfl1 '= '' p_value ''.'
* INTO ls_where
* SEPARATED BY space.
*APPEND ls_where TO lt_where.
* Creation of the "where" clause
APPEND p_where1 TO lt_where.
* Creation of the "having" clause
l_having = 'count(*) >= 1'.
* THE dynamic select
SELECT (lt_sel_list)
FROM (p_tabnam)
INTO CORRESPONDING FIELDS OF TABLE <lt_outtab>.
* WHERE (lt_where).
Hi Sanket,
The above given logic of mine works for you, put the code in the If condition and try-
just like below:
IF NOT P_EBELN IS INITIAL.
lt_where = '& = ''&'' '.
REPLACE '&' WITH p_ebeln INTO lt_where.
REPLACE '&' WITH field_value INTO lt_where.
SELECT (lt_sel_list) INTO CORRESPONDING FIELDS OF TABLE <lt_outtab>
FROM (p_tabnam)
WHERE (lt_where).
ENDIF.
thanks\
Mahesh
Similar Messages
-
Absolute dynamic select query with dynamic join and where
Has anyone ever tried creating an absolutely dynamic SELECT query with dynamic Join and Where conditions.
I have a requirement of creating such a query in an Utility Class, and i have written the code. But its throwing my sysntax errors.
Please let me know where am I going wrong OR is it really possible to create such a dynamic Query??
SELECT (FIELDS) INTO TABLE IT_TABLES
FROM ( (ME->TABLE1) inner join ( me->table2 )
on ( on_condition ) )
WHERE (me->where_fields).
Ags.It worked for me in a following way:
select * into corresponding fields of table <result_table>
from (join_string)
where (l_where).
Where the contents of join_string were dynamically build using concatenation. So it will be something like
concatenate ME->TABLE1 'as a INNER JOIN' me->table2 'as b ON (' into join_string separated by space.
<...>
add here matching/reference colums, something like
concatenate 'a~' me->TABLE1_JOIN_COL into temp1.
concatenate 'b~' me->TABLE2_JOIN_COL into temp2.
concatenate join_string temp1 '=' temp2 into join_string separated by space.
<...>
concatenate join_string ')' into join_string separated by space.
And then use similar approach for l_where variable. -
Select query with optional where condition
Hi,
Can Anybody help me out in the following problem?
I have the following query in a procedure.
SELECT replace(shipper_name,'\',' ') as shipper,
sum(teus / cntSailings) as teus
FROM VW_CONTRIBUTION,
VW_TOTAL_SAILINGS
WHERE VW_CONTRIBUTION.dir = VW_TOTAL_SAILINGS.DIR
AND VW_CONTRIBUTION.line = VW_TOTAL_SAILINGS.LINE
AND VW_CONTRIBUTION.accounting_month = VW_TOTAL_SAILINGS.ACCOUNTING_MONTH
AND VW_CONTRIBUTION.accounting_year = VW_TOTAL_SAILINGS.ACCOUNTING_YEAR
AND VW_CONTRIBUTION.Principal = arg_principal
AND VW_CONTRIBUTION.Dir = arg_direction
AND VW_CONTRIBUTION.line in ( arg_service )
AND VW_CONTRIBUTION.POL_country = arg_pol
AND VW_CONTRIBUTION.POd_country = arg_pod
AND VW_CONTRIBUTION.salesOffice = arg_SalesOffice
AND VW_CONTRIBUTION.salesregion = arg_SalesRegion
AND VW_CONTRIBUTION.cargo_type = arg_txtCargoType
AND VW_CONTRIBUTION.eqgroup = arg_ContType
AND VW_CONTRIBUTION.eq_size = arg_txtSize
AND VW_CONTRIBUTION.acct_date between arg_from_date and arg_end_date
GROUP BY shipper_name
ORDER BY teus desc;
Here some of the arguments are optional(Eg : VW_CONTRIBUTION.salesOffice, AND VW_CONTRIBUTION.eqgroup etc. ) and the values can be null. When they are null, I want them to be excluded from the where condition. Can anybody suggest me a solution for this?
Thanks,
Shalet.I guess i misunderstood your original question.
The clause
AND (VW_CONTRIBUTION.salesOffice = arg_SalesOffice OR VW_CONTRIBUTION.salesOffice IS NOT NULL)
will cause the where clause to evaluate to FALSE anytime salesOffice IS NULL so the record will be excluded.
I thought you were asking how to not compare the value if the field contained a NULL.
Glad you found what you wanted. -
How to write the select query with complex where condition
Hi all,
Can u help me in writing following select query.
select * from zu1cd_corr where time_stamp between firstday and lastday .
In the above query time_stamp contains the date and time.
where as firstday and lastday contains the dates.
I need to compare the date in the time_stamp with the firstday and lastday.
But time_stamp contains the time also and it is char of 14 characters length.Hi,
If that is the case u can do as advait specified....
if the firstday and secondday are select-options then declare two more variables having 14 character length and then concatenate '000000' to firstday variable and '240000' to last day variable and then write ur query.
CLEAR : lv_firstday,
lv_lastday.
concatenate firstday '000000' to lv_firstday.
concatenate lastday '240000' to lv_lastday.
ranges : r_Date for zu1cd_corr-time_stamp.
r_date-sign = 'I'.
r_date-option = 'BT'.
r_Date-low = lv_firstday.
r_Date-high = lv_lastday.
append r_date.
select * from zu1cd_corr into table it_zu1cd_corr where time_stamp in r_Date.
I hope it helps.
Regards,
Nagaraj -
Dynamic Select Query including Dynamic Tables with For all Entries
Hello everyone,
I need to create a select query which involves using of Dynamic Tables.
Suppose I have a dynamic table <d1> which consist of let say 10 records.
Now i need to make a select query putting data into another dynamic table <d2>
CONCATENATE keyfield '=' '<d1>' INTO g_condition SEPARATED BY space.
CONCATENATE g_condition '-' keyfield INTO g_condition.
SELECT * FROM (wa_all_tables-name) INTO CORRESPONDING FIELDS OF TABLE <d1>
FOR ALL ENTRIES IN <d1>
WHERE (g_condition).
But it is giving dump.
Please help me on this....Short text
A condition specified at runtime has an unexpected format.
What happened?
Error in the ABAP Application Program
The current ABAP program "ZNG_CUSTOMWRITE" had to be terminated because it has
come across a statement that unfortunately cannot be executed.
Error analysis
An exception occurred that is explained in detail below.
The exception, which is assigned to class 'CX_SY_DYNAMIC_OSQL_SEMANTICS', was
not caught in
procedure "WRITE_ARCHIVE_PROD" "(FORM)", nor was it propagated by a RAISING
clause.
Since the caller of the procedure could not have anticipated that the
exception would occur, the current program is terminated.
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 "ZCOURIER-ZCOURIERID".
CONCATENATE keyfield '=' g_header INTO g_condition SEPARATED BY space.
CONCATENATE g_condition '-' keyfield INTO g_condition.
SELECT * FROM (wa_all_tables-name) INTO CORRESPONDING FIELDS OF TABLE <dyn_table1>
FOR ALL ENTRIES IN <dyn_table>
WHERE (g_condition). -
Single SQl Query with different where conditions
Experts,
I have a requirement to design a report. Here are the details
I have Report table layout
Profit center Gross sales (This Year) Gross Sales (Last Year) % change Year of Year
The Report has a selection of entering the Start Date.
I have a single table in oracle which has profit center and Gross Sales Values on daily basis.
I want to write a single sql query to calculate both Gross Sales current year and Gross Sales Last Year. I can calculate Gross Sales Current Year by putting the where condition for start date = Current Year Date which i pass through report. I want to calculate the Gross Sales Last Year in the Same query by putting the different where condition i.e start date = Last Year date based on the date input.
I dont know how to put two where conditions in single query for two different columns.
Any help will be appreciated.
Thanks in advance
Regards
Santoshinstead of changing your where clause couldn't you just determine the yearly totals from your table and then use the lag statement to get last years total?
something like this?
I just made up 10,000 days worth of sales and called it fake table it is supposed to represent a variant of the table you were describing as your base table.
with fake_table as
( select trunc(sysdate + level) the_day,
level daily_gross_sales
from dual
connect by level < 10001
select yr, year_gross_sale, lag(year_gross_sale) over (order by yr) prev_year_gross_sale,
(year_gross_sale - lag(year_gross_sale) over (order by yr))/year_gross_sale * 100 percent_change
from
(select distinct yr, year_gross_sale from
select the_day,
daily_gross_sales,
extract(year from the_day) yr,
extract(year from add_months(the_day,12)) next_yr,
sum(daily_gross_sales) over (partition by extract(year from the_day)) year_gross_sale
from fake_table
order by yr
) -
Query with two where conditions
HI
SELECT ENAME FROM EMP WHERE
SAL > 1000 AND JOB='CLERK';
How to implement in CMP(Entity bean)
thank uat this point mapping to do this king of query would be on the container specific file. I will tellyou how this is done on a Orion App server. I bet that others are close to the same.
first you make a finder method in your bean for the enploy name:
Collection findBigClerk();
Orion generates a file from the ejb-jar.xml file called orion-ejb-jar.xml. this is where the O/R mapping is changed for the beans.
each method in a bean has short definition
<finder-method query="EMP.SAL>1000 and EMP.JOB='CLERK'">
Assuming that the CMP is mapped to the EMP table when you call findbigClerk it will add the above query to as a WHERE clause.
Then get the name from the interface.
Again, this is how I would do this on an Orion App server. Others will be simular until O/R mapping is moved from server-specific to the ejb-jar.xml file
hope this helps a little -
Select query for rows where condition 1
Say I have a table, tb1, that has the following entries:
FName LName
Code
John Doe
xxx
Jane Doe
xxx
Steve Harper
x
Barrak Obama
x
George Bush
xxxx
Bill Clinton
xx
I'd like to write a select query that only lists the rows where the count for Code is > 1, i.e not display the last two rows from the above entry. How would I go about writing that select query.
Thanks.Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums.
>> Say I have a table, tb1, that has the following entries: <<
Are you this rude or really ignorant and too lazy to read the Netiquette at the start to this forum? Why do you think you do not need a key? No DDL? No constraints? And , why, why do you think that “tb1” is a precise, ISO-11179 conforming table name?
Let's make this a table of rude posters rated on a 4-star scale.
CREATE TABLE Rude_Posters
(first_name VARCHAR(15) NOT NULL,
last_name VARCHAR(15) NOT NULL,
PRIMARY KEY (first_name, last_name),
rudeness_code VARCHAR (4) NOT NULL
CHECK (rudeness_code IN ('x', 'xx', 'xxx', 'xxxx'));
INSERT INTO Rude_Posters
VALUES
('John', 'Doe', 'xxx'),
('Jane', 'Doe', 'xxx'),
('Steve', 'Harper', 'x'),
('Barrack', 'Obama', 'x'),
('George', 'Bush', 'xxxx'),
('Bill', 'Clinton', 'xx');
>> I'd like to write a SELECT query that only lists the rows where the count for rudeness_code is > 1, i.e not display the last two rows from the above entry. <<
The rudeness scale is based on stars, so to ask for an integer value is like saying “on a scale from 1 to 10, what is the color of your favorite letter of the alphabet?”
Next, the number of stars and your narrative do not match. Did you want to say WHERE rudeness_code IN ('xx' 'xxx', 'xxxx')?
Please stop programming SQL until you have gotten more education. At this point, you do not know enough to ask a question.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
Dynamic Tag Query with dynamic tag name.
Hi,
In our implementation we have 10+ users. Each one want to monitor only one production line ( eg. one tag value ) in the dashboard by default when they login.
I was able to design this requirement CONCEPTUALLY but facing some trouble technically.
Here is my issue.
Tagname will be coming from one of the BLS Transaction input parameters (Transaction.Tagname). I am able to build tag query using xMII Tag Query block, able to configure repeater. Here is the spot where I was struck. While assigning tag value to XML Row
i.e IlluminatorRow_0.Tagvalue = Repeater_0.Output{/Row/AssetUtil1}.
In the above assignment link it requires a hardcoded tagname. In my case it will be dynamic. I tried different ways like
1. IlluminatorRow_0.Tagvalue = Repeater_0.Output{/Row/@Transaction.Tagname}.
2.IlluminatorRow_0.Tagvalue = Repeater_0.Output{/@Transaction.Tagname}.
But no luck.
Can someone help in how to do this dynamic tagname assignment.
Thanks,
Srinivasa.Hi Srinivas,
another option is to use "Dynamic Links" which from your sample code is what you were trying to do. For this, the proper syntax is:
Repeater_0.Output{/Row/#Transaction.Tagname#}
Make sure that the tag name you pass to the historian is the same as the tag name returned by the historian as part of the data set, and make adjustments for that. For example, some historians escape non-alphanumeric characters when they process your request (e.g. passing "abc.def 12-rt" as the tag name can be returned from the historian as "ABC.DEF_12_RT", etc.).
Hope this helps,
Sascha -
Issue in select query with where clause
Hi guys,
I'm facing an issue while using select query with the where clause. When I'm selecting all the data from the table it returns the correct result. But when I'm using the where clause to get the specific rows from the table it returns no rows. But the data I'm trying to fetch using the where condition exists in the table.
Here is my query which causing the issue,
select * from mytable where myfield = 'myvalue'
But if I use the following query it returns the result correctly.
select * from mytable
Also the myfield value 'myvalue' exists in the table.
I have tried by running this query in both SQL Developer and SQL Plus. I have tried this query in mssql as well. It works perfectly and returns correct result sets for both the queries I have mentioned above. I'm unable to predict the issue as I'm new to ORACLE. Please help.
Thanks,
Ram.Hi Ram,
I experienced an issue similar to this with a varchar2 field. Some of our records had a hidden newline character at the end of them, which was making queries like the one below fail:
select * from employees
where email = '[email protected]'The best way I found to detect this was to use
select 'XX'||email||'XX' from employeesTo make sure that there were no newlines. But that is just a guess. If you could provide some example table data and the outputs of your selects, it would be helpful.
Jeff -
Dynamic select list with display,return val & join condition issue.
hello,
I am having a dynamic select list with display, return value
say for example my select statement is
select distinct dname d, deptno r
from dept dt
right join emp e on (e.deptno=dt.deptno)
where (condition)
when i tried this query for my select list, it is not working. It saying that
" LOV query is invalid, a display and a return value are needed, the column names need to be different. If your query contains an in-line query, the first FROM clause in the SQL statement must not belong to the in-line query. "
I am not able to understand the problem. Can anyone help me out with this issue?
thanks.Shouldn't your join have dept as the driving table?
select distinct dname d, deptno r
from dept dt
right join emp e on (dt.deptno = e.deptno)
where (condition)
Or using older Oracle standard join
select distinct dname d, deptno r
from dept dt, emp e
where (dt.deptno (+) = e.deptno) AND (OTHER WHERE condition)
OR
(Since a right join is just getting the values from the driving table that are NOT in the associated table)
select distinct dname d, deptno r
from dept dt
WHERE dt deptno NOT IN (SELECT deptno FROM emp) AND (OTHER where condition)
Thank you,
Tony Miller
Webster, TX -
How to create a Type Object with Dynamic select query columns in a Function
Hi Every One,
I'm trying to figure out how to write a piplined function that executes a dynamic select query and construct a Type Object in order to assigned it to the pipe row.
I have tried by
SELECT a.DB_QUERY INTO actual_query FROM mytable a WHERE a.country_code = 'US';
c :=DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(c,actual_query,DBMS_SQL.NATIVE);
l_status := DBMS_SQL.EXECUTE(c);
DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
FOR j in 1..col_cnt LOOP
DBMS_SQL.DEFINE_COLUMN(c,j,v_val,2000);
END LOOP;
FOR j in 1..col_cnt LOOP
DBMS_SQL.COLUMN_VALUE(c,j,v_val);
END LOOP;
But got stuck, how to iterate the values and assign to a Type Object from the cursor. Can any one guide me how to do the process.
Thanks,
mallikj2Hi Justin,
First of thanks for your reply, and coming to my requirement, I need to report the list of items which are there in the dynamic select statement what am getting from the DB. The select statement number of columns may vary in my example for different countries the select item columns count is different. For US its '15', for UK it may be 10 ...like so, and some of the column value might be a combination or calculation part of other table columns (The select query contains more than one table in the from clause).
In order to execute the dynamic select statement and return the result i choose to write a function which will parse the cursor for dynamic query and then iterate the values and construct a Type Object and append it to the pipe row.
Am relatively very new for these sort of things, welcome in case of any suggestions to make it simple (Instead of the function what i thought to work with) also a sample narrating the new procedure will be appreciated.
Thanks in Advance,
mallikj2. -
Dynamic Select query is failing with error "Invalid Table Name"
OPEN rc FOR 'SELECT count(*) from :s' USING tab_name;
fetch rc into rec_count;
CLOSE rc;
my requirement is to build dynamic select query to retrieve the total count of rows in each table ( variable tab_name contains the table_name )
But I am getting stuck by this errror, not sure if there is any alternative !
ORA-00903: invalid table name
ORA-06512: at line 43OPEN rc FOR 'SELECT count(*) from '||tab_name;
fetch rc into rec_count;
CLOSE rc;
-- This will work
1. Create a sql statement.
2. Open ref cursor for that statement. -
How to use Field-symbol with dynamic select query
Can anybody tell me, how to use field-symbols in the dynamic select query.
FIELD-SYMBOLS <fs> { typing | STRUCTURE struc DEFAULT dobj }.
1. ... typing
2. ... STRUCTURE struc DEFAULT dobj
The FIELD-SYMBOLS statement declares a field symbol <fs>. The name conventions apply to the name fs. The angle brackets of the field symbols indicate the difference to data objects and are obligatory. You can declare field symbols in any procedure and in the global declaration section of an ABAP program, but not in the declaration section of a class or an interface. You can use a field symbol in any operand position in which it is visible and which match the typing defined using typing.
After its declaration, a field symbol is initial - that is, it does not reference a memory area. You have to assign a memory area to it (normally using the ASSIGN statement) before you can use it as an operand. Otherwise an exception will be triggered.
eg.
FIELD-SYMBOLS <fs> TYPE ANY.
DATA: BEGIN OF line,
string1(10) VALUE '0123456789',
string2(10) VALUE 'abcdefghij',
END OF line.
WRITE / line-string1+5.
ASSIGN line-string1+5(*) TO <fs>.
WRITE / <fs>.
output:
56789
56789
reward if helpful
anju -
Select query with variable no of conditions
Hi,
I want to write a select query such that the conditions mentioned under WHERE clause can be variable .like :
Select * from TABLE where F1 = var1 and F2 = var2 and F3 = var3.
Now on the basis of some conditons the equations in where clause should be used.Say condition is variable value >6.
Now in this case ,if
var1 =7 var2 =3 var3 = 8 then the query shud behave like
select * from TABLE where F1 = var1 and F3 = var3
if :
var1 =3 var2 = 4 var3 =3 the :
select * from TABLE
But only one query is to be wrote that satisfies all of these
thanx
Edited by: aachal on Feb 4, 2011 11:36 AMHi Aachal,
Use Dynamic select statement.
Ex:
data : lv_wherecond type string.
Select * from TABLE where ( lv_wherecond ).
Before Select stmt, code as follows.
if var1 > 6.
if lv_wherecond is initial.
F1 = var1.
else.
concatenate lv_wherecond ' and F1 = var1' into lv_wherecond.
endif.
elseif var 2 > 6.
if lv_wherecond is initial.
F2 = var2
else.
concatenate lv_wherecond ' and F2 = var2' into lv_wherecond.
endif.
elseif var3 > 6.
same as above ..
endif.
Hope it helps..
Regards,
Sravan Guduru.
Maybe you are looking for
-
Trouble With Port Mirroring (SG200-08)
Trouble with port mirroring. Even though both Tx and Rx is specified, only getting half the conversation. Ping reply only for instance. And when pinging from other locations no traffic at all. Please help SG200-008 FW Version: 1.0.2.0 Boot Version
-
Slow motion not playing back after 8.02
I have iPhone 6 plus. I shot a couple of slow-motion videos when device had iOS 8.0. I just noticed that these videos are not playing back in slow-mo after the upgrade to iOS 8.02. Anybody else having this problem? Any suggestions?
-
Text file 'engineOnClose.txt'
I keep getting the following text file 'engineOnClose.txt' everytime I quit my browser. Does anybody know why I'm getting this file, as I've not see it before?
-
HT201210 my phone just says that i need to connect to itunes but thats it what do i do now?
my phone says to connect to itunes. but its not letting me what do i do now?
-
Can i upgrade OSX10.4.11 straight to 10.6?
Can i upgrade OSX10.4.11 straight to 10.6? I need to update and screen share in ichat, as well as other stuff... and 10.4.11 is too old now. But i cant get 10.4.11 to10.5 disc.... so wondered if i can just stick 10.6 in and install over everything? A