Conditional Mysql select statement
HI Folks
can anyone point me in the right direction with a MySQL statement.
I will try to layout my thinking here:
I have a form with three inputs area, name and search. I am trying to write a Mysql select statement that selects records from a single table if they match the criteria. Easy for two variables but I'm lost after that.
1. The form includes these three inputs:
area - drop down menu (Any as default)
name - drop down menu (Any as default)
search box - text area (Blank as default)
2. The form submits to itself leaving me with these three variables
$search=$_GET['search']
$area=$_GET['area']
$name=$_GET['area']
SELECT * FROM database WHERE database.description LIKE '%$search%' AND database.area LIKE '$area' AND database.name LIKE '$name'
3. This is where I get confused. How do I get the SQL to Select everything correctly. I have tried using PHP if/else code to fix it but I end up running around in circles with six different Select statements and haven't yet got that to work.
So I have come to the conclusion that there must be an easier way. I see search forms with dozens of search criteria on websites every day an d I only have 3 - so it can't be this complicated. Right?
I know I need to start from the beginning again but can anyone let me know how to approach it before I begin?
Cheers
Dave
Typically, I would build the where clause dynamically, based upon the values in your form. If the form field contains 'Any', leave it out of the where clause. So you can test each field value and either append or not to the end of the where clause.
Similar Messages
-
MySQL Select Statement Help Required
I am trying to generate a report in VS 2008 (C#) using a mysql select statement but cannot get it right.
I have groups that meet on a weekly basis on different days. I want to generate a report that shows me all the members that have not attended their group where they have missed 3 meetings in a row.
Below is the select statement I have tried but it does not give me the results I am looking for. I have tried to look at all the meetings in a 4 week period but would prefer to look at the last 3 meetings that are recorded. Some groups might not record a meeting every week. So I want to look at the last 3 recorded meetings and count each members attendance and only report on the members with more than 3 meetings missed.
SELECT COUNT(`groupattendance`.`Attended`) AS Attendance, `smallgroupform`.`MeetingDate`, `userinfo`.`FirstName`, `userinfo`.`Surname`, `smallgroup`.`GroupName`, `groupattendance`.`Attended`, `groupattendance`.`UserID`, `groupattendance`.`GroupID`
FROM ((`anatomy`.`groupattendance` `groupattendance`
INNER JOIN `anatomy`.`smallgroupform` `smallgroupform` ON `groupattendance`.`FormID` = `smallgroupform`.`FormID`)
INNER JOIN `anatomy`.`userinfo` `userinfo` ON `groupattendance`.`UserID` = `userinfo`.`UserID`)
INNER JOIN `anatomy`.`smallgroup` `smallgroup` ON `groupattendance`.`GroupID` = `smallgroup`.`GroupID`
WHERE (`smallgroupform`.`MeetingDate` >= DATE_SUB(CURDATE(),INTERVAL 4 WEEK) AND `smallgroupform`.`MeetingDate` <= CURDATE()) AND `groupattendance`.`Attended` = 'False'
GROUP BY `userinfo`.`UserID`
HAVING Attendance >= 3
Thanks,
Garth.Hi Garth,
Seems no one can help you directly. Try googling your SQL request. Someone may be able to help you. At this point its not really a Cr problem.
One option is to get all the data and add filtering using the record selection formula.
Thank you
Don -
Concat java variable to a MySql select statement and exeucte
Hi,
I am trying to append a variable to a MySql select statement.
Overview: I need to retrieve data from a MySql database with a java variable as a reference and select the data in the database based on that variable.
CODE THAT I CURRENTLY HAVE:
// Declare variables
Connection conn = null;
Statement st = null;
Resultset rs2 = null;
String st2 = null;
String keyid = null;
// Connect to database
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://" + mysql_host + ":3306/" + mysql_database, mysql_login, mysql_password);
st = conn.createStatement();
// Select data in Database with hanging equal sign
st2 = ("SELECT * FROM table WHERE keyid= ");
// Append keyid to hanging equal sign of select statement
rs2 = st.executeQuery(st2 + keyid);
}This is not working when I try to display the data.What is not working about it? Is there an error message? Stack Trace?
Where do you get the value of keyId from?
I would suggest that you use a prepared statement rather than building up a sql string like this. It prevents sql injection attacks
// Declare variables
Connection conn = null;
PreparedStatement stmt = null;
Resultset rs2 = null;
String sql= null;
String keyid = null;
// Connect to database
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://" + mysql_host + ":3306/" + mysql_database, mysql_login, mysql_password);
// Select data in Database with place holder for parameter
sql = "SELECT * FROM table WHERE keyid= ?";
// prepare the statement
stmt = conn.prepareStatement(sql);
// set the value of key id to use with the query
stmt.setString(1, keyId);
// run the query
rs2 = st.executeQuery();
catch (Exception e){
System.out.println("An error occurred " + e.getMessage());
e.printStackTrace();
finally{
if (rs2 != null) try { rs2.close(); } catch(SQLException ex){}
if (stmt != null) try { stmt.close(); } catch(SQLException ex){}
if (conn != null) try { con.close(); } catch(SQLException ex){}
} -
Dynamic where condition in Select statement
Hi,
I have 10 fields on selection-screeen. In which ever field the user enters single values or ranges,i should pick that field dynamically and pass that field along with value range to Where condition of Select statement.How can i achieve this? Please help.
Regards
K Srinivassee the following example:
data : begin of itab occurs 0,
matnr like mara-matnr,
end of itab.
ypes: begin of ty_s_clause.
types: line(72) type c.
types: end of ty_s_clause.
data : begin of gt_condtab occurs 0.
include structure hrcond.
data : end of gt_condtab.
FIELD-SYMBOLS <fs_wherecond> TYPE ty_s_clause.
data:
gt_where_clauses type standard table of ty_s_clause
with default key.
gt_condtab-field = 'MATNR'.
gt_condtab-opera = 'EQ'.
gt_condtab-low = '000000000000000111'.
append gt_condtab.
clear gt_condtab.
call function 'RH_DYNAMIC_WHERE_BUILD'
exporting
dbtable = space " can be empty
tables
condtab = gt_condtab
where_clause = gt_where_clauses
exceptions
empty_condtab = 01
no_db_field = 02
unknown_db = 03
wrong_condition = 04.
select matnr from mara into table itab where (gt_where_clauses). -
Checking conditions in SELECT statement
Hi All,
I am relative new to ABAP and I would like to ask a question about checking conditions in SELECT statement in the "WHERE" part.
There are two checkboxes at the selection screen and each should disable one of conditions (marked with two stars) in the SELECT mentioned below.
My question is, whether there exists an option how to solve this problem without using solution like:
IF checkobx1.
SELECT (without one condition)
ELSEIF checkbox2.
SELECT(without other condition).
ELSE.
SELECT (with both conditions)
SELECT qprueflos qherkunft qaufnr qsa_aufnr qmatnr qwerkvorg
qpastrterm qpaendterm
qverid qobjnr vobjnr AS objnr_fa vauart
FROM qals AS q INNER JOIN vkaufk AS v
ON qaufnr = vaufnr
INTO CORRESPONDING FIELDS OF TABLE gt_qals
WHERE q~prueflos IN s_pruefl
AND q~stat35 EQ space
AND q~werk EQ loswk
AND q~herkunft IN s_herk
AND q~offennlzmk EQ 0
AND q~offen_lzmk EQ 0
AND q~pastrterm IN s_startt
AND q~paendterm LE s_endt
AND v~auart IN s_auart. "('ZCPA', 'ZCPK', 'ZCBA').Hi,
With this, I think u can directly read into WHERE clause
IF checkbox1.
v_where = '& BETWEEN ''&'' AND ''&'' '.
REPLACE '&' WITH key_field INTO v_where.
REPLACE '&' WITH field_LOW INTO v_where.
REPLACE '&' WITH field_HIGH INTO v_where.
CONDENSE v_where.
ELSEIF checkbox2.
v_where = '& BETWEEN ''&'' AND ''&'' '.
REPLACE '&' WITH key_field INTO v_where.
REPLACE '&' WITH field_LOW INTO v_where.
REPLACE '&' WITH field_HIGH INTO v_where.
CONDENSE v_where.
ENDIF.
select * into corresponding fields of table ITAB
from (table_name)
where (v_where).
In this key_field is your fieldname in the where clause and field_low, field_high are range of values.
If i write static query it looks like this
RANGES: MATNR1 FOR MARA-MATNR.
MATNR1-LOW = MATNR_LOW.
MATNR1-HIGH = MATNR_HIGH.
MATNR1-SIGN = 'I'.
MATNR1-OPTION = 'BT'.
APPEND MATNR1.
select * into corresponding fields of table itab
from mara where matnr BETWEEN 'M100' AND 'M200'.
Hope it helps u
thanks\
Mahesh
Edited by: Mahesh Reddy on Jan 30, 2009 11:23 AM -
MySql select statement in jsp page
Ok,
I need help with this select statement.
<%
// Determine what option is set to.
if(option == null || "".equals(option) || "Verify1".equals(option)){
if("Verify1".equals(option)){
// Retrive query specific to submitted form.
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://" + mysql_host + ":3306/" + mysql_database, mysql_login, mysql_password);
st = conn.createStatement();
rs= st.executeQuery("SELECT organization FROM tblevent_approval WHERE MAX (keyid))";
// Get query results.
while(rs.next()){
organization = rs.getString("organization");
finally {
if(rs != null){
rs.close();
if(st != null){
st.close()
if(conn != null){
conn.close();
%>THE ERROR I AM GETTING
Syntax error, insert ")" to complete ExpressionThis line has the closing bracket inside the closing quote for the statement...
> rs= st.executeQuery("SELECT organization FROM tblevent_approval WHERE MAX (keyid))";It should be:
rs= st.executeQuery("SELECT organization FROM tblevent_approval WHERE MAX (keyid)");A simple typo ;-)
Hope this helps... -
Hi All,
I have java application which suppose to connect to MySql server and print the selected data.
The application has 4 combo boxes (first item is empty): Name, Customer, Supplier, Status.
User could choose any of these options. So there are huge number of select combinations.
Is it possible to create one select statement template something like this:
PreparedStatement stmt = con.prepareStatement( "SELECT * from database WHERE user_id = ?,
and customer_id = ?,
and supplier_id = ?,
and status = ? " );
if ( ! ComboBox.getSelectedItem().toString().isEmpty() )
stmt00.setString( 1, ComboBox.getSelectedItem().toString() );
else
stmt00.setString( 1, "*" );
etc
I'm stuck at this part stmt00.setString( 1, "*" ). Is there any way to write statement SELECT * from table WHERE column = * ?
What is the proper way to write such selection ?
Thanks in advance,
VladimirIs there any way to write statement SELECT * from table WHERE column = * ?No, that's invalid SQL.
What is the proper way to write such selection ?If you need in one case to select a single user, but in another case to select all of them, then you need to handle two different SQL statements.
1. SELECT * from table WHERE column = value
2. SELECT * from table
This has nothing to do with Java. -
Please help - NE where condition in SELECT statement
Dear experts,
I am posting a section of my codes here for your review on performance tuning.
In my second select statement, I used a "NE" where condition. I read somewhere in this forum that using "NE" where condition is not a good decision for improving codes' performance. What alternatives can I have to achieve the same purpose? May I use "NOT IN" here instead? Or do I use a LOOP for this (a rather manual way)?
Just to let you all know that I still consider myself quite inexperienced in ABAP - please also let me know how I can better improvise my programming techniques in the posted codes here too.
I will be most glad to provide you with further information if needed - just let me know.
Many THANKS in advance!
IF p_noncis = 'X'. " Non CIS category of spend selected
" zfi_cis_mat_grp is a bespoke table that stores all CIS MATKL
" and it has two fields only - MANDT and MATKL
SELECT * FROM zfi_cis_mat_grp
INTO TABLE gt_cis_mat_grp.
IF gt_cis_mat_grp IS NOT INITIAL.
SELECT ebeln
ebelp
matkl
FROM ekpo
INTO TABLE gt_ekpo
FOR ALL ENTRIES IN gt_cis_mat_grp
WHERE matkl NE gt_cis_mat_grp-matkl. " NE where condition - is this OK?
ENDIF.
IF gt_ekpo IS NOT INITIAL.
IF s_sakto IS NOT INITIAL.
SELECT ebeln
ebelp
sakto
FROM ekkn
INTO TABLE gt_ekkn
FOR ALL ENTRIES IN gt_ekpo
WHERE ebeln = gt_ekpo-ebeln AND
ebelp = gt_ekpo-ebelp AND
sakto IN s_sakto.
IF gt_ekkn IS NOT INITIAL.
SELECT bukrs
lifnr
belnr
budat
cpudt
xblnr
ebeln
ebelp
zfbdt
zterm
zlspr
FROM bsik
INTO TABLE gt_bsik
FOR ALL ENTRIES IN gt_ekkn
WHERE bukrs IN s_bukrs AND
lifnr IN s_lifnr AND
budat IN s_budat AND
cpudt IN s_cpudt AND
xblnr IN s_xblnr AND
ebeln = gt_ekkn-ebeln AND
ebelp = gt_ekkn-ebelp AND
qsskz NE ''.
ENDIF.
ELSE.
SELECT bukrs
lifnr
belnr
budat
cpudt
xblnr
ebeln
ebelp
zfbdt
zterm
zlspr
FROM bsik
INTO TABLE gt_bsik
FOR ALL ENTRIES IN gt_ekpo
WHERE bukrs IN s_bukrs AND
lifnr IN s_lifnr AND
budat IN s_budat AND
cpudt IN s_cpudt AND
xblnr IN s_xblnr AND
ebeln = gt_ekpo-ebeln AND
ebelp = gt_ekpo-ebelp AND
qsskz NE ''.
ENDIF.
ENDIF.
ELSE. " Complete list of category of spend selected
SELECT bukrs
lifnr
belnr
budat
cpudt
xblnr
ebeln
ebelp
zfbdt
zterm
zlspr
FROM bsik
INTO TABLE gt_bsik
WHERE bukrs IN s_bukrs AND
lifnr IN s_lifnr AND
budat IN s_budat AND
cpudt IN s_cpudt AND
xblnr IN s_xblnr AND
qsskz NE ''.
ENDIF.Hi,
If you want to remove th NE option then try this way..
SELECT bukrs
lifnr
belnr
budat
cpudt
xblnr
ebeln
ebelp
zfbdt
zterm
zlspr
FROM bsik
INTO TABLE gt_bsik
WHERE bukrs IN s_bukrs AND
lifnr IN s_lifnr AND
budat IN s_budat AND
cpudt IN s_cpudt AND
xblnr IN s_xblnr .
IF SY-SUBRC EQ 0.
Delete gt_bsik where qsskz EQ ' '.
ENDIF. -
Mysql select statement where = works and LIKE fails
I am using Flash Builder 4. On the server side I use php and mysql. I created a php dataservice using FB4. My plan had been to allow users to enter a search term and query the database using a "LIKE" statement. FB4 created the php code that I simply modified changing the parameter name. The input parameter is a string.
public function getT_caseByID($searchTerm) {
$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename WHERE (title = ?)");
$this->throwExceptionOnError();
mysqli_stmt_bind_param($stmt, 'i', $searchTerm);
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
mysqli_stmt_bind_result($stmt, $row->idt_case, $row->title, $row->id_author, $row->comments);
if(mysqli_stmt_fetch($stmt)) {
return $row;
} else {
return null;
A look at FB4 shows this code returns data.
This code works fine but if I make the below change it fails, even when I use the wildcard %. the only change is "=" to "LIKE".
public function getT_caseByID($searchTerm) {
$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename WHERE (title LIKE ?)");
$this->throwExceptionOnError();
mysqli_stmt_bind_param($stmt, 'i', $searchTerm);
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
mysqli_stmt_bind_result($stmt, $row->idt_case, $row->title, $row->id_author, $row->comments);
if(mysqli_stmt_fetch($stmt)) {
return $row;
} else {
return null;
A look into FB4 shows "void".
Any help would be appreciated. I am using localhost on Apache Server on a development computer with Windows XP.correctio0n on the select statement
select statement code*********
select
apspnr astspr aobjnr apspid
bpsphi bposid
caufnr cpspel
dinact dstat
eudate eusnam eutime "estat
F~TXT04
g~estat
G~TXT04
into corresponding fields of table itobj
from proj as a
inner join prps as b on apspnr = bpsphi
inner join aufk as c on bpspnr = cpspel
inner join jest as d on cobjnr = dobjnr
inner join jcds as e on dobjnr = eobjnr
and dstat = estat
inner join tj02t as f on estat = fistat
inner join tj30t as g on astspr = gstsma
for all entries in itparm
where apspid = itparm-pspid "or estat = itparm-psy )
or bposid = itparm-posid "or estat = itparm-wsy )
or caufnr = itparm-aufnr "or estat = itparm-nsy )
and ( dinact 'X' or einact 'X')
and fspras = 'E' and gspras = 'E'. -
i want to check this condition ina select statement
if clearing date in s_cldate or clearing date
is greater than key date
wat will be the syntaxSELECT * from <table name>
INTO TABLE <itab>
WHERE cldate IN S_CLDATE
OR cldate GT key_date .
IF s_date contains SINGLE date rather than range then.
READ TABLE S_CLDATE INDEX 1.
SELECT * from <table name>
INTO TABLE <itab>
FOR ALL ENTRIES IN S_CLDATE
WHERE cldate GT S_CLDATE-LOW.
Regards,
Swarup.
Edited by: swarup basagare on Jun 20, 2008 8:51 AM -
REG:- SELECT STATEMENT IN IF CONDITION.
HI FRIENDS,
CAN V USE SELECT STATEMENT IN IF CONDITION LIKE....
IF (SELECT COUNT(EMPID) FROM EMPLOPYEE) > 1 THEN
UPDATE STATEMENT;
END IF;
PLEASE HELP.
--RAJNISHHi,
1. Hit the Caps Lock key hard in your key board.
2. Put your code between tags for better readability.
3. When you have a where clause, why do you want to go for if clause? as in
[code]
update <your_table> set <your_col> = <your_new_val>
where (select count(empid) from employee) > 1
[/code]
is logically equivalent to your
[code]
if (select count(empid) from employee) > 1 then
update statement;
end if;
[/code]
-Arun -
Using Select statement in IF condition?
hi all,
Can i use select statement in IF COndition in pl sql ?
eg like- if( select 1 from ASD) then
end if;There is no way to do any kind of select statement inside if conditions.
Why don't test simple cases like this first?
An example to show it.
SQL> begin
2 if exists (select 1 from dual) then
3 dbms_output.put_line('ok');
4 end if;
5 end;
6 /
if exists (select 1 from dual) then
ERRORE alla riga 2:
ORA-06550: line 2, column 5:
PLS-00204: function or pseudo-column 'EXISTS' may be used inside a SQL
statement only
ORA-06550: line 2, column 2:
PL/SQL: Statement ignored
SQL> begin
2 if ( (select count(*) from dual) > 0 ) then
3 dbms_output.put_line('ok');
4 end if;
5 end;
6 /
if ( (select count(*) from dual) > 0 ) then
ERRORE alla riga 2:
ORA-06550: line 2, column 8:
PLS-00103: Encountered the symbol "SELECT" 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 alternativ
ORA-06550: line 2, column 33:
PLS-00103: Encountered the symbol ")" when expecting one of the following:
. , @ ; for <an identifier>
<a double-quoted delimited-identifier> group having intersect
minus order partition start subpartition union where connect
SQL> begin
2 if ( 0 in (select count(*) from dual) ) then
3 dbms_output.put_line('ok');
4 end if;
5 end;
6 /
if ( 0 in (select count(*) from dual) ) then
ERRORE alla riga 2:
ORA-06550: line 2, column 12:
PLS-00405: subquery not allowed in this context
ORA-06550: line 2, column 2:
PL/SQL: Statement ignoredBye Alessandro -
Select statement in if/else condition
Hi i need to write a select statement in the if condition in pl/sql how can i write this
example :
if field_name not in (select statement) then
Is this type of if condition is possible in pl/sql?
thanks in advance for help.Qwerty wrote:
here pick a job example salesman for ename ward, now i want to compare this job that is "salesman" with all the jobs which are before it. that is clerk in line 1 and salesman in line 2Define "before it". There is no order in relational tables. Only ORDER BY means ordered sets. Therefore there is no before/after without ORDER BY. Assuming ORDER BY empno, job count of same job title before empno:
select ename,
job,
count(*) over(partition by job order by empno) - 1 same_job_count_before_empno
from emp
ENAME JOB SAME_JOB_COUNT_BEFORE_EMPNO
SCOTT ANALYST 0
FORD ANALYST 1
SMITH CLERK 0
ADAMS CLERK 1
JAMES CLERK 2
MILLER CLERK 3
JONES MANAGER 0
BLAKE MANAGER 1
CLARK MANAGER 2
KING PRESIDENT 0
ALLEN SALESMAN 0
ENAME JOB SAME_JOB_COUNT_BEFORE_EMPNO
WARD SALESMAN 1
MARTIN SALESMAN 2
TURNER SALESMAN 3
14 rows selected.To find job count of same job title as Ward has before Ward (by empno):
SELECT same_job_count_before_empno
FROM (
select ename,
count(*) over(partition by job order by empno) - 1 same_job_count_before_empno
from emp
WHERE ename = 'WARD'
SAME_JOB_COUNT_BEFORE_EMPNO
1SY. -
1 Conditional report based on 3 select lists/ 3 different select statements
I have made 1 report based on the three select lists. The report is displayed in the center of the page. The user needs to fill them in order, the select lists are:
Selectlist:
1. P1_LOVPG - Null is allowed, but is only appearing at top with a label of Productgroup
2. P1_LOVSG - Null is allowed, but is only appearing at top with a label of Subgroup
3. P1_LOVMA - Null is allowed, but is only appearing at top with a label of Manufacturer
LOVPG contains a distinct collect of the ProductGroups
QUERY LOV = select distinct pg from X
LOVSG contains a distinct collect of the SubGroups inside the selected PG.list
QUERY LOV = select distinct sg from X where pg = :P1_LOVPG
LOVMA contains a distinct collect of the Manufacturers inside the selected SG.lst
QUERY LOV = select distinct ma from X where sg = :P_LOVSG
Based on the the selected items the user would see the following:
Table X
PG SG MA ART
A-----X----M---1
A-----X----N---2
A-----Y----M---3
A-----X----M---4
B-----X----M---5
B-----Y----N---6
B-----Z----O---7
Seletion 1 PG = A -> selects PG A in select list result, User sees:
Report A
PG SG MA ART
A-----X----M---1
A-----X----N---2
A-----Y----M---3
A-----X----M---4
Query would be: select * from X where PG = :P1_LOVPG
Selection 2, user still sees the above, can only select from the SG select list NULL, X, Y. User needs to choose between X or Y value. He picks X, he sees:
Report B
PG SG MA ART
A-----X----M---1
A-----X----N---2
A-----X----M---4
Query would be: select * from X where PG = :P1_LOVPG and SG = :P_LOVSG
Selection 3, user still sees selection 2 on his screen, can only select from the MA list bewteen NULL, M or N, user needs to choose between M or N. He picks M, he sees:
Report C
PG SG MA ART
A-----X----M---1
A-----X----M---4
Query would be: select * from X where PG = :P1_LOVPG and SG = :P_LOVSG
As you can see the query changes as the user goes deeper into the structure. It is a simple if then else system where the quey changes. How do I set this up in htmldb?
(I've read something about Oracle's SQL and it's decode function, but can they be used with changing select statements?)are you sure your data meets the JOIN conditions?
You can make a quick check.. only example...
select single * from KONP into ls_konp
where knumh = P_knumh.
if sy-subrc eq 0.
select * from from A905 into table lt_a905 where
kappl in so_kappl
and kschl in so_kschl
and VKORG in so_vkorg
and vtweg in so_vtweg
and kondm in so_kondm
and wkreg in so_wkreg
and knumh = ls_konp-knumh.
if sy-subrc eq 0.
select * from A919 into table lt_a919
for all entries in lt_a905
where kappl = lt_a905-kappl
and kschl = lt_905-kschl
and knumh = lt_905-knumh.
endif.
endif. -
Field symbols as Table name and in where condition in a select statement
Hello All,
I have a scenario where I need to get user input on table name and old field value and new field value. Then based on user input, I need to select the record from the database. The column name for all the tables in question is different in the database, however there data type is the same and have same values.
I am not able to use a field symbol for comparing the old field value to fetch the relevant record in my where clause.
I cannnot loop through the entire table as it has 10 millilon records, please advice on how to add the where clause as field symbol as the table name is also dynamically assigned.
Here is my code:
DATA: TAB LIKE SY-TNAME,
TAB_COMP1 LIKE X031L-FIELDNAME,
TAB_COMP2 LIKE X031L-FIELDNAME,
NO_OF_FLD TYPE N.
DATA: BEGIN OF BUFFER,
ALIGNMENT TYPE F,
C(8000) TYPE C,
END OF BUFFER.
FIELD-SYMBOLS: <WA> TYPE ANY,
<COMP1> TYPE ANY,
<COMP2> TYPE ANY.
GET TABLE NAME GIVEN BY USER IN LOCAL VARIABLE
TAB = TAB_NAME.
CREATE FIELD NAME BASED ON THE TABLE NAME ENTERED.
CASE TAB_NAME.
WHEN 'OIUH_RV_GL'.
KEY FIELD
TAB_COMP1 = 'GL_GL_SYS_NO'.
NO_OF_FLD = 1.
WHEN 'OIUH_RV_OPSL'.
KEY FIELD
TAB_COMP1 = 'OPSL_GL_SYS_NO'.
NO_OF_FLD = 1.
WHEN 'OIUH_RV_OTAX'.
NOT THE ONLY KEY FIELD
TAB_COMP1 = 'OTAX_GL_SYS_NO'.
TAB_COMP2 = 'OTAX_TAX_POS_NO'.
NO_OF_FLD = 2.
WHEN 'OIUH_RV_GTAX'.
NOT THE ONLY KEY FIELD
TAB_COMP1 = 'GTAX_GL_SYS_NO'.
TAB_COMP2 = 'GTAX_TAX_POS_NO'.
NO_OF_FLD = 2.
WHEN OTHERS.
EXIT.
ENDCASE.
SET FIELD SYMBOL WITH APPROPRIATE TYPE TO BUFFER AREA.
ASSIGN BUFFER TO <WA> CASTING TYPE (TAB).
How to add where clause and remove the if condition in the select -- endselect
SELECT * FROM (TAB) INTO <WA>.
ASSIGN COMPONENT TAB_COMP1 OF STRUCTURE <WA> TO <COMP1>.
IF NO_OF_FLD = 2.
ASSIGN COMPONENT TAB_COMP2 OF STRUCTURE <WA> TO <COMP2>.
ENDIF.
IF <COMP1> = OLD_SYS_NO.
code for updating table would come here
WRITE: 'MATCH FOUND'.
EXIT.
ENDIF.
ENDSELECT.
Please advice. Thanks much.
Edited by: Shipra Jhunjhunwala on Jul 22, 2009 1:33 PM
Edited by: Shipra Jhunjhunwala on Jul 22, 2009 1:34 PM
Edited by: Shipra Jhunjhunwala on Jul 22, 2009 1:35 PM1. Create single column table for holding field name depending on the table entered.
2. Take input from user: for e.g. table_name
3. Using case load single column table with required fields
for e.g.
CASE TAB_NAME.
WHEN 'OIUH_RV_GL'.
Append 'GL_GL_SYS_NO' to KEY_FIELD --> KEY_FIELD is the single line internal table as mentioned in step 1.
WHEN 'OIUH_RV_OPSL'.
Append 'OPSL_GL_SYS_NO'.
WHEN 'OIUH_RV_OTAX'.
Append 'OTAX_GL_SYS_NO' to KEY_FIELD.
APPEND 'OTAX_TAX_POS_NO' to KEY_FIELD.
WHEN 'OIUH_RV_GTAX'.
Append 'GTAX_GL_SYS_NO' to KEY_FIELD.
APPEND 'OTAX_TAX_POS_NO' to KEY_FIELD.
WHEN OTHERS.
EXIT.
ENDCASE.
Now depending on the table name you have required column ready
4. Create dynamic internal table using following sudo code
Fill the fieldcatlog using the single column field table and DD03L table, See what all columns from DD03L you want to fill in field catlog table
loop at internal table with all the fields.
move it to field catalog.
append field catalog.
endloop.
5. Pass this field catalog table to static method create_dynamic_table method
DATA table TYPE REF TO DATA. --> data object for holding handle to dynamic internal table.
call method cl_alv_table_create=>create_dynamic_table
exporting
it_fieldcatalog = fieldcatalog_tab
importing
ep_table = table.
6. Now assign table reference to field symbol of type table.
ASSIGN table->* to <field-tab>.
7. Also create work area <field-wa> using refrence of table.
create data object wa LIKE LINE OF <field-tab>.
ASSIGN wa->* to <field-wa>.
8. Also define field symbol for field name.
for e.g. <field_name>
4. Dynamic internal table is ready
5. Now execute the select statement as follows:
SELECT (KEY_FIELD)
INTO <ITAB> --> created dynamically above
FROM (TABLE_NAME)
WHERE (WHERE). --> WHERE is single line internal table having line type of CHAR72. So for every old value there will be one line
Where condition is same as like we give in static way only difference in this case it will stored in internal table line wise.
In this case you need to append all your where condition line by line in to WHERE.
5. To fill this dynamic internal table using ASSIGN COMPONENT <Comp_number> OF STRUCTURE <field-wa> TO <field-name>
So in this case if first field of structure STRUCT1 is user_id then sudo-code will be
loop at internal table containing list of fields into field_wa --> single column field table
ASSIGN COMPONENT field_wa OF STRUCTURE <field-wa> TO <field>. "Here field_wa is wa area for single column internal table holding all the fieldnames.
Now <field-name> points to user_id field. Move some value into it as nornally we do with variables.
Move <your_new_value> to <field-name>. --> Assign new value
or
<field-name> = <your_new_value>.
Endloop.
6. After completing all the fields one row will be ready in <field_wa>.
APPEND <field_wa> to <field_tab>.
Hope this helps you.
Thanks,
Augustin.
Maybe you are looking for
-
Satellite L300 - Is overheating and shuts down
I've just got my laptop back after getting it fixed (new HDD & BIOS/FW update according to the sheet that came with it). But now another problem has developed with the laptop overheating & auto shutting down a lot as a result. Is there any way to che
-
Control of Text box in Dialog programming
Hai Friends i am having problem in controlling the Text box in PAI of Screen. For eg. if it is command button with the use of Function name i can able to check or do validation in PAI. As in the case of Textbox how to give the name for the text box a
-
My friend and I are both using iPhones and our messages are not blue. Both of our I messages are turned on.
-
Best way to manage external photo collection with iPhoto?
I have a large collection of photos that now resides on an external NAS drive. I used Canon ZoomBrowser EX software on Windows to download the images from my cameras, but I want to start using iPhoto on my MacBook instead. There's no metadata associa
-
Recording quality problem..can anyone help?
I have found Audition to be a wonderful tool for my audio restoration work, and so it was natural for me to use it when I started recording my own music. I write 2-4 songs a month, andI have been struggling for years to perfect my guitar tones. I ha