Use variable in SQL statement
HI guys:
I need code three SQL statements.the returned field and selected table are all same,there is only a difference in their "where" statement.
Sample code:
select marcmatnr marcwerks
into table it_data
from MARC inner join MBEW on marcmatnr = mbewmatnr
where marcmatnr like 'A%' and mbewzplp1 = '001'.
second one........................ mbew~zplp2 = '001'
third one......................... mbew~zplp3 = '001'
Could I write a FORM gather them with transporting a parameter ZPLPX to determine which condiniton will be execute?
thank you very much.
Hi tianli,
1. source text
This concept of dynamic where
condition is called source text.
2. use like this.
This is important in the code ---> WHERE (mywhere).
REPORT abc LINE-SIZE 80.
DATA : it_data LIKE TABLE OF mara WITH HEADER LINE.
QUOTES ARE IMPORTANT
PERFORM mysql USING 'mbew~zplp2 = ''001'''.
FORM mysql USING mywhere.
SELECT marcmatnr marcwerks
INTO TABLE it_data
FROM marc INNER JOIN mbew ON marcmatnr = mbewmatnr
WHERE (mywhere).
ENDFORM. "mysql
regards,
amit m.
Similar Messages
-
PL SQL using variable in SQL statement
I am trying to execute several sql statements, that have the same format but different values. Does this
mean I need a bind variable?
ie
select TO_CHAR ( (SYSDATE - 2), 'YYYY_MM_DD') from dual
select TO_CHAR ( (SYSDATE - 4), 'YYYY_MM_DD') from dual
select to_char(add_months(sysdate,-2*1) from dual
When I try to put the values into a varaiable (date, varchar2 or number) I am getting a conversion
error.
Can somebody show me an example of how to do something like this? Or at least point me to the correct
part of the documentation that provides and example. Pardon my syntax as I know it is incorrect
val :=add_months(sysdate,-2*1
select to_char(val) from dual
Thanks in advance to all who answerHi,
840386 wrote:
I am trying to execute several sql statements, that have the same format but different values. Does this
mean I need a bind variable?No, you don't need a bind variable, though bind variables may be more efficient than using PL/SQL variables. I don't see where you're trying to use any varibables at all in your examples. Is it in place of the literals, such as 2 or 'YYYY_MM_DD'? You can use either bind varibales or PL/SQL variables in those places.
ie
select TO_CHAR ( (SYSDATE - 2), 'YYYY_MM_DD') from dual
select TO_CHAR ( (SYSDATE - 4), 'YYYY_MM_DD') from dual
select to_char(add_months(sysdate,-2*1) from dualIn PL/SQL, when you have a SELECT statement, you must specify what you want to do with the results. For example, a SELECT ... INTO statement:
SELECT AVG (sal)
INTO avg_salary
FROM scott.emp;There's usually no point in SELECTing from dual in PL/SQL. It's not an error, but it's simpler just to use an assignment statement.
When I try to put the values into a varaiable (date, varchar2 or number) I am getting a conversion
error.Post a complete procedure or anonymous block, including variable declarations, that shows exactly what you're trying to do.
>
Can somebody show me an example of how to do something like this? Or at least point me to the correct
part of the documentation that provides and example. Pardon my syntax as I know it is incorrect
val :=add_months(sysdate,-2*1Assuming val is a DATE, that's basically correct. You have unbalanced parentheses (there's a '(', but no matching ')' ), and you need a semicolon (';') at the end of the statement. Perhaps ');' just got cut off when you were posting this.
select to_char(val) from dualAgain, SELECTing from dual is unnecessary, but if you had some way to catch the returned value, that would work.
Usually, the reason why you need to call TO_CHAR is that you want a value in a particular format, which is specified in the 2nd argument to TO_CHAR. Calling TO_CHAR with only one argument is a possible mistake, but not something that would raise an error.
Here's an example that works:
SET SERVEROUTPUT ON
DECLARE
d DATE;
v VARCHAR2 (30);
BEGIN
d := ADD_MONTHS (SYSDATE, -2); -- -2 = (-2*1)
v := TO_CHAR (d, 'DD-Mon-YYYY');
dbms_output.put_line (v || ' = v');
END;
/Output (when run on March 13, 2011):
13-Jan-2011 = v -
HELP - using variables in SQL statement
Hi,
I am sure that this is a small problems for the gurus out there.
I am trying to execute the following statement usign JDBC:
String myVariable = "XYZ";
sSQL = "select COL1, COL2 from TABLE1 where COL3 = '" + myVariable + "'";
CODE ABOVE DOES NOT WORK FOR ME!!!!!
HOWEVER, if I were to directly substitute the value XYZ as shown below, then things work. But that does not solve my problem.
sSQL = "select COL1, COL2 from TABLE1 where COL3 = '" + "XYZ" + "'";
Any suggestions?
nullUse methods setXXXX of the PreparedStatement class.
Connection conn =
DriverManager.getConnection("jdbc:default:connection:");
PreparedStatement stm=conn.prepareStatement(
"select name from persons where inn=?");
String inn="ASDDGF12345";
String name=new String;
stm.setString(1,inn);
ResultSet rss = stm.executeQuery();
if (rss.next())
name = rss.getString(1);
rss.close();
stm.close();
conn.close(); -
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. -
Hello All,
I am getting below error can you please help me
Error:-
The transaction associated with the current connection has completed but has not been disposed. The transaction must be disposed before the connection can be used to execute SQL statements.Perhaps this thread will help you out
http://stackoverflow.com/questions/11453066/error-the-transaction-associated-with-the-current-connection-has-completed-but
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
Using bind variables with sql statements
We connect from a VB 6.0 program via OO4O to an Oracle 8.1.7 database, using bind variables in connection with select statements. Running ok, but performance again by using bind vars not as good as expected!
When looking into the table v$sqlarea, we were able to detect the reason. We expected that our program submits the sql statement with bind vars, Oracle parses this once, and with each select statement again, we do not have a reparse. But: It seems that with each new session Oracle reparses the sql statement, that is, Oracle is not able to memorize or cache bind vars and statements. Even more worrying, this kind of behaviour was visible with each new dynaset, but the same database/session.
Is there anybody our there with an idea of what is happening here?
Code snippet:
Dim OraSession As OracleInProcServer.OraSessionClass
Dim OraDatabase As OracleInProcServer.OraDatabase
Set OraSession = CreateObject("OracleInProcServer.XOraSession")
Set OraDatabase = OraSession.OpenDatabase(my database", "my connect", 0&)
OraDatabase.Parameters.Add "my_bind", 0, ORAPARM_INPUT
OraDatabase.Parameters("my_bind").DynasetOption = ORADYN_NOCACHE
OraDatabase.Parameters("my_bind").serverType = ORATYPE_NUMBER ' Bind Var Type
Dim RS As OracleInProcServer.OraDynaset
strSQLstatement= "Select * from my_table where igz= [my_bind] "
Set RS = OraDatabase.CreateDynaset(strSQLstatement, &H4)
OraDatabase.Parameters("my_bind").Value = myValue
RS.Refresh
Cheers and thanks a lot :)
Michael SonntagWe connect from a VB 6.0 program via OO4O to an Oracle 8.1.7 database, using bind variables in connection with select statements. Running ok, but performance again by using bind vars not as good as expected!
When looking into the table v$sqlarea, we were able to detect the reason. We expected that our program submits the sql statement with bind vars, Oracle parses this once, and with each select statement again, we do not have a reparse. But: It seems that with each new session Oracle reparses the sql statement, that is, Oracle is not able to memorize or cache bind vars and statements. Even more worrying, this kind of behaviour was visible with each new dynaset, but the same database/session.
Is there anybody our there with an idea of what is happening here?
Code snippet:
Dim OraSession As OracleInProcServer.OraSessionClass
Dim OraDatabase As OracleInProcServer.OraDatabase
Set OraSession = CreateObject("OracleInProcServer.XOraSession")
Set OraDatabase = OraSession.OpenDatabase(my database", "my connect", 0&)
OraDatabase.Parameters.Add "my_bind", 0, ORAPARM_INPUT
OraDatabase.Parameters("my_bind").DynasetOption = ORADYN_NOCACHE
OraDatabase.Parameters("my_bind").serverType = ORATYPE_NUMBER ' Bind Var Type
Dim RS As OracleInProcServer.OraDynaset
strSQLstatement= "Select * from my_table where igz= [my_bind] "
Set RS = OraDatabase.CreateDynaset(strSQLstatement, &H4)
OraDatabase.Parameters("my_bind").Value = myValue
RS.Refresh
Cheers and thanks a lot :)
Michael Sonntag -
Using variable in select statement (php)
I am having difficulty using a variable in a select
statement.
The following manual query (using a static date) works fine:
$query_Recordset1 = "SELECT * FROM academyClasses WHERE
classDate > '2006-06-01' ";
However, If I use the following:
$dateVar = date('Y-m-d');
mysql_select_db($database_mw, $mw);
$query_Recordset1 = "SELECT * FROM academyClasses WHERE
classDate > $dateVar ";
ALL records are returned, which means the $dateVar variable
is not being recognized. I have compared the $dateVar values
<?php echo $datetime; ?> against the actual value of my date
field <?php echo $row_Recordset1['classDate']; ?> in my
results table and it seems that the values are indeed accurate in
terms of a date 2006-06-04 for example.
My date field "classDate" is of a "date" type within the
mysql database. I'm using Dreamweaver MX 2004 with Mac OSX 10.3.9.
I'm sure this is just a syntax problem, at least I hope it
is.
Any help is greatly appreciated.On Wed, 7 Jun 2006 04:49:57 +0000 (UTC), "mgwaters"
<[email protected]> wrote:
>Thanks Gary. That did seem to get the select statement
working, but I had to
>enter a manual date as before $dateVar = '2006-06-01'; on
the previous line of
>code to actually get it to filter my records. So... it
looks like my setting of
>the date variable:
> $dateVar = date('Y-m-d');
> does not seem to be recognized within the SELECT
statement.
Try this:
$query_Recordset1 = "SELECT * FROM academyClasses WHERE
classDate>'$dateVar'";
print $query_Recordset1;
See what is in the SQL statement.
Gary -
Using Procedure in SQL statement
Dear Sir,
As you know, I can use any function in SQL statement. For example:
SELECT systimestamp,
Function_Name(variable1, variable2,...)
FROM anytable;
So the previous function could only retrieve one value -as functions concepts-. Anyhow, Can I, in someway, use Procedure that take multiple in parameters and return multiple out parameters in SQL statement.
Thank you in advance.Sir,
I got a way in order to use the benefit of procedure in function. It's trough your idea in using TYPE OBJECT as the following:
===================================================================
create or replace type Missed_Txn_type AS OBJECT
(Txn_Timestamp_obj timestamp,
Txn_Type_Obj Number(12));
===================================================================
Then I created function and used this type as returned value:
FUNCTION Get_Shift_Missed_Txn_Obj(F_Date_In Date,
F_Time_In Timestamp,
F_Employee_Id number)
RETURN Missed_Txn_type;
The issue is: I want send the variables of the function through SELECT statement which they come from another table like:
SELECT
EMP.ID,
sd.date_value,
shf.Time_In,
T.OBJ.Txn_Timestamp_obj,
T.OBJ.Txn_Type_Obj
FROM
EMPLOYEE EMP,
Stored_Date SD,
Shifts shf,
(select Get_Shift_Missed_Txn_Obj(sd.date_value,
shf.time_in,
EMP.Id) OBJ from dual) T
WHERE
[where clause]
But the previous statement returned an error shows that it couldn't determine the (EMP.ID, shf.time_in, sd.date_value...)...
And the same if I use it in the select list!
So sir, there is any way in order to solve this issue?
Thank you in advance. -
Function or pseudo-column 'DECODE' may be used inside a SQL statement only
Hi everyone!
I got the error in the subject concernig the follow piece of sql code
+ v_str_sql_body :=
v_str_sql_body || ' and cod_entita ='
|| decode(cur.cod_entita_a,str_all,cur_ent.cod_entita,cur.cod_entita_a);
execute immediate v_str_sql_body; +
I can't understand what's the problem with it.
Can anyone help me to find the error?
Thank you in advance!
Samuel
Edited by: 996508 on 27-mar-2013 5.29Hi, Samuel,
Welcome to the forum!
996508 wrote:
Hi everyone!
I got the error in the subject concernig the follow piece of sql code
+ v_str_sql_body :=
v_str_sql_body || ' and cod_entita ='
|| decode(cur.cod_entita_a,str_all,cur_ent.cod_entita,cur.cod_entita_a);
execute immediate v_str_sql_body; +
I can't understand what's the problem with it.Sorry, I can't understand what you're trying to do.
Whenever you have a problem, post a complete script that people can run to re-create the problem and test their ideas. Include your complete PL/SQL code (if the problem involves PL/SQL) including code to call your procedure, a little sample data (CREATE TABLE and INSERT statements) for any tables involved, and the results you want the given sample data.
Always say which version of Oracle you have (e.g., 11.2.0.3.0).
See the forum FAQ {message:id=9360003}
Can anyone help me to find the error?As the error message says, you can only use DECODE in a SQL statement. That is:
v_str_body := v_str_body
|| ' and cod_entita = '
|| DECODE (...);is always an error, no matter what ... stands for.
Perhaps you meant to have the DECODE inside the string literal.
If not, then (depending on your version) you can use CASE instead of DECODE:
v_str_body := v_str_body
|| ' and cod_entita = '
|| CASE cur.cod_entita_a
WHEN str_all THEN cur_ent.cod_entita
ELSE cur.cod_entita_a
END;Anything that DECODE can do, CASE can do, too.
DECODE is sometimes a little simpler than CASE to use, but only a little. It is never faster than CASE.
CASE is sometimes much, much simpler to use than DECODE, and sometimes much faster, too.
I won't say never use DECODE; but I will say rarely use DECODE. Use CASE instead, unless you have a specific reason why DECODE is better in that particular situation.
In PL/SQL, you can also use IF ... THEN ... ELSE in places where you might want to use DECODE or CASE.
For example:
v_str_body := v_str_body
|| ' and cod_entita = ';
IF cur.cod_entita_a = str_all
THEN
v_str_body := v_str_body
|| cur_ent.cod_entita;
ELSE
v_str_body := v_str_body
|| cur.cod_entita_a;
END IF;Edited by: Frank Kulash on Mar 27, 2013 5:59 PM
Added IF ... THEN ... ELSE example. -
Same WITH used in many SQL statements
Hi,
I have a need to use the same WITH clause in many places of my code. Is it ever possible to code without writing the same code in every SQL which need my WITH?
Thanks in advance.As Tubs mentioned, views.
There only 2 basic methods of modularisation of SQL source code. Using the WITH clause (modularises in the same statement), or VIEWS (modularises across SQL statements).
Using PL/SQL functions or pipelined tables are poor choices for SQL code modularisation. And should not be considered. These tools address a different set of requirements. -
Bind Variables in SQL Statement
can someone tell me if there is a way to find out what the bind variables values are in an sql statement extracted from any of the v$sql or v$sqlarea type tables ?
sql example:
update DTree set OriginOwnerID=:A
where OriginOwnerID=:B and OriginDataID=:C
Thanks
JimHi damorgan
i see two ot of the three:
SQL> desc gv$sql_bind_capture
ERROR:
ORA-04043: object gv$sql_bind_capture does not exist
i just trying to see what bind variable values would be associated with the sql when i extract the sql from v$sql and if that is even possible
Thanks
Jim -
How to swap column values using variable in sql?
Hi,
I have a table and i want to swap two column values using variable
please help meHi,
Let us assume that the DeptNAME and DeptNo columns are of type VARCHAR2. However, DeptNO column is VARCHAR2(10) and DeptNAMe is VARCHAR2(100).
First of all DeptNo column needs to be modified to be 100.
i) ALTER TABLE DEPT MODIFY DEPTNO VARCHAR2(100);
Secondly, you will swap DEPTNAME and DEPTNO values using the SQL as follows:
ii) update dept t1
set deptname = (select deptno from dept2 t2 where t1.deptno = t2.deptno),
deptno = (select deptname from dept2 t2 where t1.deptno = t2.deptno);
Now, finally you want the deptname columns to be VARCHAR2(10)
iii) ALTER TABLE DEPT MODIFY DEPTNAME VARCHAR2(10).
If DEPTNO is a NUMBER column, you cannot alter the datatype unless the table is empty; in that case the whole swapping requirement would be moot.
Trinath Somanchi,
( http://www.myospages.com ) -
Is it possible to pass or set a variable in SQL LOADER? In this case I want the file name (eg $data) that is getting passed from the command line to load into my table into the extract_date field.
For example. The command line:
sqlldr user/password control=deposit.ctl data=080322.txt
Control file:
Load data
infile '$data'
Append into table deposit
, id position (1-10)
, extract_date date "YYMMDD" $data
Any thoughts?user567866 wrote:
Is it possible to pass or set a variable in SQL LOADER? In this case I want the file name (eg $data) that is getting passed from the command line to load into my table into the extract_date field.
For example. The command line:
sqlldr user/password control=deposit.ctl data=080322.txt
Control file:
Load data
infile '$data'
Append into table deposit
, id position (1-10)
, extract_date date "YYMMDD" $data
Any thoughts?Just wonder, why do you need a variable, if you are passing the filename on the command line? The sqlldr is perfectly capable to read the data from the file given as argument with parameter data. Just remove the line with infile from your controlfile and leave your commandline as is.
Best regards
Maxim -
Maxl - can you use variables in iferror statements
hi guys,
A quick one:
Can you use variables when doing error handling? I assume the answer is yes, but just wanted to make sure.
example:
set app1 = Test;
set app1_db1 = Test;
alter database $app1.$app1_db1 force archive to file "C:\\EssbaseBackup\\$app1\\$app1_db1\\$app1_db1.arc";
iferror 'Bk_$app1.$app1_db1_Error';
define label 'Bk_$app1.$app1_db1_Error';
exit 10;
I am putting error handling into my script and want to double check before I go about making the alterations.
Many thanks,
Russell
Edited by: RussellH-C on 26-Apr-2013 04:45You don't need to split the files. Create a Maxl with parameters and then call it in a bat file.
In the bat you can then check for Error.
essmsh -D "%HYP_MONTH_SCRIPTS_DIR%\Maxl_Files\HYP_ESS_Archive.msh" %DECRYPTKEY% Appname1 Dbname1
call :archiveerrcheck
essmsh -D "%HYP_MONTH_SCRIPTS_DIR%\Maxl_Files\HYP_ESS_Archive.msh" %DECRYPTKEY% Appname2 Dbname2
call :archiveerrcheck
archiveerrcheck:
SET FILE=%MAXLLOG_DIR%\Archive.log
findstr /R "\<ERROR" %FILE% > ESSErrCheck
for /F %%A in ("ESSErrCheck") do If %%~zA NEQ 0 (
call :datestamp
echo Error in Archive Process......................... > %ESSLOG%
copy %FILE% %HYP_MONTH_ERR_DIR%\Essbase\MaxL\Maxl_Error.log
DEL /Q ESSErrCheck
call :exit_process
) else (
echo %DTSTMP% Log Out Process was successfull......................... >> %ESSLOG%
call :remove_file ESSErrCheck
GOTO EOF
:EOFRegards
Celvin
http://www.orahyplabs.com -
Can we use repository variables in SQL statement of column prompt?
Hi Dudes,
Below is the query
SELECT "- End Date"."End Fiscal Year" FROM "Consumer Sector" WHERE ("- End Date"."End Fiscal Year" = valueof (current_year)) or ("- End Date"."End Fiscal Year" = valueof (current_year) -1)
when use this sql in criteria prompt getting error.
Please suggest .
thanks.sriMake sure your syntax is correct it should be like VALUEOF("CURRENT_YEAR")-1
If you still have issues then VALUEOF("CURRENT_YEAR")-1 cast it to int before you subtract.
If helps pls mark as correct else let share error message
Maybe you are looking for
-
Apple ID for home sharing and iTunes Store should be the same?
I've got 2 iTunes Store accounts, my girlfriend has one, and we're just moving in together. A few questions ... Can I create a 4th 'Apple ID' for our home sharing? Would we still be able to listen to each others libraries? Would we still be able to c
-
Report: Statistical WBS elements with assets assigned to them - actual cost
Hi all, I would like to run a report that gave me this info: WBS Element (all statistical) Assets assigned to each WBS Actual costs It would be perfect CJI3 but it doesn't show assets. In AM I haven't see either any report that shows WBS elements...
-
JVM1.4.2 What can cause many full gc to occur in a row ?
Hi, I'm seeing many fullgc occuring in a row on a web application runing under tomcat 5.0.28/mod_jk System is Solaris 9, 4 proc Java version is : 1.4.2_10 JVM Parameters are : -server -d64 -Xmn640m -Xms2048m -Xmx2048m -XX:ParallelGC Threads=2 -XX:+Us
-
SRM 7.0 - add a new column to POWL
Hi, I want to add a new column (number of follow-on document) to the shopping cart POWL. How can I enhance the feedertype SAPSRM_FEEDER_SC with custom fields? Thanks and best regards, Roman
-
How to Correct this Select Statement...?
hi all i wrote a select as follows select datediff('HH',to_date(job_start,'hh24:mi:ss'),to_date('15:29:59','hh24:MI:ss')) from shift requirement is to calculate the hours used in a shift, the job_start column is date type and having value '23/08/2007