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?
null
Use 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();
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 -
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. -
Help Using Count and SQL statements
Hello
This problem has been bugging me incesantly and I would be reaaaaaaally grateful if someone could help here
I want to create query that woud count the number of times a certain unedited word would be matched against different edited words
This query works well in MS ACCess but not in java
query =" SELECT Count(*) AS WordCount, Segmentations.EditedWord FROM [select Segmentations.EditedWord FROM Segmentations where Segmentations.UneditedWord = '"+Word+"']. AS c GROUP BY Segmentations.EditedWord";
I've tried removing the Segmentations. and changing it to
query =" SELECT Count(*) AS WordCount, EditedWord FROM [select EditedWord FROM Segmentations where UneditedWord = '"+Word+"']. AS c GROUP BY EditedWord";
But still nothing
I think that is due to the fact that you can't call Count(*) and another field at the same time
pleas eif anyone knows a way around this send it ASAP
thanxWhy not use,
query = "SELECT Count(*) AS WordCount, EditedWord FROM Segmentations WHERE UneditedWord = ? GROUP BY EditedWord"and use PreparedStatement to optimize.
HTH -
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 -
Hello,
I would like to use integer array( say..int count[] = new int[3];) on my sql statement to retrieve some values. Is there a way to use int array variable in sql statement?. If yes, how should I approach doing that?.
Thank You in Advance.
Regards,
Pinal.I'm going to be honest, I'm not so sure there is such a thing in standard SQL syntax so it would depend upon the database you were using as to whether this option was available as part of the SQL language.
My suggestion would be to cheat, naughty I know:String arrayString = "";
for (int i = 0; i < arrayInt.size(); i++) {
arrayString += "**" + arrayInt;
arrayString = arrayString.substring(2, arrayString.length());Then just parse arrayString in to an SQL VARCHAR or TEXT field.
Obviously when you return it just use StringTokenizer to split the string up using your deliminator (in this case **) and then convert the values back into an int array.
I'm not sure how efficient that code would be but it should do the job. -
Using 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 -
Can someone help me correct this sql statement in a jsp page?
ive been getting the java.sql.SQLException: Incorrect syntax error for one of my sql nested statements. i cant seem to find similar egs online, so reckon if anyone here could help, really appreciate it.
as im putting the nested sql in jsp page, it has to be with lots of " " n crap. very confusing if there are nested.
heres the sql statement without those "" that i want to use:
select top 5 * from(
select top+"'"+offset+"'"+" * from prod where cat=" +"'" cat "'"+"
)order by prodID desc
when i put this in my jsp pg, i had to add "" to become:
String sql = "select top 5 * from("+"select top"+"'"+offset+"'"+" * from prod where cat=" +"'" +cat+ "'"+")order by prodID desc";cat=" +"'" cat "'"+")order by prodID desc";
all those "" are confusing me to no end, so i cant figure out what should be the correct syntax. the error says the syntax error is near the offset.If offset is, say, 10, and cat is, say, "new", then it looks like you're going to produce the SQL:
select top 5 * from(
select top '10' * from prod where cat='new'
)order by prodID descThat looks exactly like incorrect syntax to me... top almost certainly can't handle a string literal as its operand... you almost certainly would want "top 10" instead of "top '10'"...
If you use PreparedStatement, you don't have to remember what you quote and what you don't and you can have your SQL in a single static final string to boot... -
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. -
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 ) -
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 -
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
Maybe you are looking for
-
Error in creation of materialzed view.
Hello All, I am trying to create a materialized view on a pre-built table. But the MV does not get created and gives an error ORA-12014. Following are the codes for MV logs and MV I am using: CREATE materialized VIEW log ON table_1 WITH rowid, sequen
-
Weird result of oracle query before and after function base index creation
Hi All, Here is the unique situation we are facing after creating just an index. The query result before the index and the query result after the index do not match. This is very illogical situation. Shidhar and me have done lot of R&D, also tried to
-
I am a new iPad Air user. How do I get back to the home page with all the icons.
I Am a new user. How do I get back to the home page with all the icons.
-
Iphone Freeze During 2.2 Update. Help please
I was updateing my brand new iphone today with the 2.2 software update and it downloaded just fine. When it started to install, I got an error in itunes and it's just sitting at the update screen not moving. It's been about 30 minutes now. Picture be
-
Why i cant watch VCD to my macbook pro, but if i play DVD it will work,
why i cant watch VCD to my macbook pro??, but if i play DVD it will work, help guys.. pleasee..