String formatting in SQL/PLSQL
How can we format strings (Varchar) using sql/plsql? Are there any functions using which I can format varchar variables. e.g., to convert an amount 100000 to 100,000.00 .
Hi Swamy,
You will get this error if you try to format a char column.
If you are sure that the value is numeric try converting by TO_NUMBER and then use the TO_CHAR function for formatting purpose.
Eg:
SQL> select to_char(to_number('643455'), '9,999,999.99') from dual;
Cheers.
Jeeva.
Similar Messages
-
Convert a String to java.sql.Date Format
Hi,
I am having a String of containing date in the format 'dd/mm/yyyy' OR 'dd-MMM-YYYY' OR 'mm-dd-yyyy' format. I need to convert the string to java.sql.Date object so that I can perform a query the database for the date field. Can any one suggest me with the code please.
Regards,
Smithaimport java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
public class TestDateFormat
public static void main(String args[])
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(sdf.isLenient());
try
Date d1 = sdf.parse("07-11-2001");
System.out.println(d1);
Date d2 = sdf.parse("07:11:2001");
System.out.println(d2);
catch(ParseException e)
System.out.println("Error format, " + e);
See class DateFormat and SimpleDateFormat for detail. -
How to convert BLOB data into string format.
Hi,
I have problem while converting blob data into string format.
for example,
Select dbms_lob.substr(c.shape.Get_wkb(),4000,1) from geotable c
will get me the first 4000 byte of BLOB .
When i using SQL as i did above,the max length is 4000, but i can get 32K using plsql as below:
declare
my_var CLOB;
BEGIN
for x in (Select X from T)
loop
my_var:=dbms_lob.substr(x.X,32767,1)
end loop
return my_var;
I comfortably convert 32k BLOB field to string.
My problem is how to convert blob to varchar having size more than 32K.
Please help me to resolve this,
Thanx in advance for the support,
NileshNilesh,
. . . .The result of get_wkb() will not be human readable (all values are encoded into some binary format).
SELECT utl_raw.cast_to_varchar2(tbl.geometry.get_wkt()) from FeatureTable tbl;
-- resulting string:
☺AW(⌂özßHAA
Å\(÷. . . .You may also want to have a look at { dbms_lob | http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_lob.htm#i1015792 } "The DBMS_LOB package provides subprograms to operate on BLOBs, CLOBs, NCLOBs, BFILEs, and temporary LOBs."
Regards,
Noel -
Problem with variables in dynamic SQL/PLSQL
Hi, I have a problem I am trying to solve using a very short piece of dynamic SQL/PLSQL but I am having problems getting the variable values out of the dynamic block.
I need to increment a counter which could be any one of 16 counters I am using and I want to avoid using nested IF statements.
The variable to be incremented is made up of the 'scheme', the 'contributory category' and the 'employment category' (although not every combination is valid)
The 'scheme' can be either 'no1', 'no2', 'off', 'cg' or 'amc'
The 'contributory category' can be either 'cont' or 'noncont'
The 'employment category' can be either 'ft' or 'pt'
For example the total variable name could be 'v_cg_noncont_ft_count'
I have created a variable by concatenating the various elements called v_incr_count_name which holds the name of the variable I want to increment.
I am running this within an anonymous PLSQL block so I cannot use global variables meaning that my variables are not visible within a dynamic PLSQL block.
As a result I think I will need to use bind variables with a PLSQL block or a SELECT FROM INTO SQL string
I have tried various solutions including the following PLSQL solution:
v_incr_count_name := 'v_'||v_scheme||'_'||v_cont_cat||'_'||v_emp_cat||'_count';
sql_stmt := 'BEGIN :a := :a + 1; END;';
EXECUTE IMMEDIATE sql_stmt USING v_incr_count_name;
Unfortunately I am getting the 'IN bind variable bound to an OUT position' error which I suppose makes sense as I am trying to change the value of a variable in the main PLSQL block from within the dynamic block.
Another (SQL) solution I tried was:
v_incr_count_name := 'v_'||v_scheme||'_'||v_cont_cat||'_'||v_emp_cat||'_count';
sql_stmt := 'SELECT '||v_incr_count_name||' + 1 FROM DUAL';
EXECUTE IMMEDIATE sql_stmt INTO v_return;
While this executes and returns the incremented value into v_return, I am still left unable to copy the returned value into the variable whose name is stored in v_incr_count_name
Any help appreciated
Cheers, Danthis shows the syntax for the using clause
declare
a number := 1;
b number := null;
v varchar2(10) := 'A';
begin
execute immediate 'begin :v1 := :v1 + 1; end;' using in out a;
dbms_output.put_line(a);
end;
/but what you want cannot be done
SQL> declare
2 a number := 1;
3 b number := null;
4 v varchar2(10) := 'A';
5 begin
6 execute immediate 'begin '||v||' := :v1 + 1; end;' using in out a;
7 dbms_output.put_line(a);
8 end;
9 /
declare
ERROR at line 1:
ORA-06550: line 1, column 7:
PLS-00201: identifier 'A' must be declared
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
ORA-06512: at line 6the variable "V" contains the name of the desired output variable ("A"). this errors because "A" is not defined within the scope of the dynamic sql.
"into the variable whose name is stored in v_incr_count_name"
pl/sql does not support dereferencing variables, so you can't do it. -
Convert a date in String format to a Date
Hi,
How can I convert a date in String format to a Date object?
I have tried:
import java.text.*;
import java.io.*;
import java.util.Date;
import java.util.Locale;
import java.sql.*;
public class casa {
public static Connection con = null;
public static Statement s = null;
public static String sql = null;
public static String mydate = "01.01.2001";
/** Creates a new instance of casa */
public casa() {
public static void main(String[] args) throws SQLException{
try {
DateFormat shortFormat = DateFormat.getDateInstance(DateFormat.SHORT);
Date date = shortFormat.parse(mydate);
//Open Database
con = getConnection();
s = con.createStatement();
sql = "select date1 from table1 where date1 <= '"+date+"'";
ResultSet rs = s.executeQuery(sql);
while(rs.next()){
String aba = rs.getString("datum");
System.out.println("New Datum = "+aba);
} catch (Exception ex ) {
ex.printStackTrace();
closeConnection(s, con);
//Connection
private static Connection getConnection() {
Connection con = null;
String user ="aouzi";
String passe ="aouzi";
String url = "jdbc:db2:EjbTest";
try {
//Datenbanktreiber laden
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
//Verbindung herstellen
con = DriverManager.getConnection(url,user,passe);
}catch(ClassNotFoundException e){
} catch(SQLException e){}
return con;
//close Connection
private static void closeConnection(Statement s, Connection con) {
try {
s.close();
} catch (SQLException e) {}
try {
con.close();
} catch (SQLException e) {}
I'm getting the following errors:
COM.ibm.db2.jdbc.DB2Exception: [IBM][CLI Driver][DB2/NT] SQL0180N
The syntax of the representation of a date/time of day value as character sequence is false. .SQLSTATE=22007I'm pretty sure it won't understand what date.toString() returns. If you know what format the database understands, you do it like this:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy"); // e.g. 18-Apr-02
String datestring = sdf.parse(date);
and use that instead of date in your sql string. Some databases understands it if you do
"to_date('18-Apr-02')"
so you could include that in your sql string as well..
You could also try to make it a java.sql.Date and hope your jdbc driver knows how to convert it to a string that the database understands if you don't know the format:
con = getConnection();
PreparedStatement ps = con.prepareStatement("select date1 from table1 where date1 <= ?");
ps.setDate(new java.sql.Date(date.getTime()));
ResultSet rs = s.executeQuery(sql); -
Hi there !
Please, can anyone help me find out what is going on with date format in my SQL Statements ?
While in development, the date format in SQL statements were:
SELECT DATA_FIELD FROM TABLE WHERE DATE_COL = '10-DEC-2004'
And works fine.
After deploy to production server, we get ORACLE error: not a valid month
So we change the format to
SELECT DATA_FIELD FROM TABLE WHERE DATE_COL = '10/12/2004'
And it gets to works again.
Yesterday, the net administrator updated the JAVAC / JSDK run-time with Java update tool, and AGAIN we get ORACLE error: not a valid month
So we change the format AGAIN to
SELECT DATA_FIELD FROM TABLE WHERE DATE_COL = '10-DEZ-2004'
And it gets to works again.
What is going on ?
JAVAC running on Windows2003.
The application access the ORACLE DB directly through JDBC.
There is no APPLICATION SERVER, like TOMCAT.
The regedit (windows registry) ALWAYS was and are now :
NLS_DATE_FORMAT = DD-MON-YYYY
NLS_LANG = AMERICAN_AMERICA.WE8ISO8859P1
Versions:
DB Oracle 9.2.0.5.0
JavaC 1.4.2.05
Thanks.
JulianoSomewhere, I'm willing to wager your NLS_DATE_FORMAT was/ is being changed. This is a client-side setting. Are you sure that the setting is the same on every client machine.
This is one of the reasons that it is considered bad form to rely on implicit conversion. If you wrap your string literal in a TO_DATE, use the JDBC escape sequence {d }, or use a Date bind variable, you don't have this problem. The bind variable approach will also play much more nicely with your database's shared pool.
Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC -
Update date format in SQL developer
I need to convert date format in SQL developer , it's varchar2 format now
The current format is yyyy/mm/dd-hh:mm:ss:sss and I need to convert it to yyyy-mm-dd hh:mm:ss CST
I don't really know SQL but did some research and found that I can use instr to find the string and replace it, however, no matter what I try,there is always something off :(
Could anyone here help me with it? thanks in advance.create table xo_custom_date_format (mydateAsChar varchar2(100));
table XO_CUSTOM_DATE_FORMAT created.
insert into xo_custom_date_format
values ('2012/03/23-09:52:24:123')
+1 rows inserted.+
select mydateasChar from xo_custom_date_format
mydateaschar
+2012/03/23-09:52:24:123+
select to_timestamp(mydateaschar, 'YYYY/MM/DD-HH24:MI:SS:FF3') mydateAsTimestamp from xo_custom_date_format
-- We must convert to timestamp data type, rather than date data type as you have fractions of seconds
mydateAsTimestamp
+23-MAR-12 09:52:24.123000000 --<-- This will probably appear differently, depending on your database NLS_ settings (i.e. what country you are in)+
select to_char( to_timestamp(mydateaschar, 'YYYY/MM/DD-HH24:MI:SS:FF3') , 'YYYY-MM-DD HH24:MM:SS')||' CST' as myDateReformatted
from xo_custom_date_format
mydateReformatted
+2012-03-23 09:03:24 CST+ -
Using a comma-delimited string in Dynamic SQL
Hi --
If I receive a comma-delimited string as an in parameter, can I simply use that (in string format) when building my dynamic sql?
Thanks,
ChristineThe problem is, that you can not use bind variables
here, only literals. This causes
eventual performance problems.And to avoid the inevitable database performance problems Dmytro mentions you can use a function to convert the string to a varray and select from that. This also avoids having to use dynamic sql.
First you create a varray and conversion function.
SQL> create or replace type tabstr_t as table of varchar2(255)
2 /
Type created.
SQL> create or replace function tabstr (
2 p_str in varchar2,
3 p_sep in varchar2 default ','
4 )
5 return tabstr_t
6 as
7 l_str long default p_str || p_sep;
8 l_tabstr tabstr_t := tabstr_t();
9 begin
10 while l_str is not null loop
11 l_tabstr.extend(1);
12 l_tabstr(l_tabstr.count) := rtrim(substr(
13 l_str,1,instr(l_str,p_sep)),p_sep);
14 l_str := substr(l_str,instr(l_str,p_sep)+1);
15 end loop;
16 return l_tabstr;
17 end;
18 /
Function created.Then you can use these in either regular sql.
SQL> var s varchar2(100)
SQL> exec :s := 'Smith,Scott,Miller'
PL/SQL procedure successfully completed.
SQL>
SQL> select * from emp where ename in
2 (select upper(column_value) from table(tabstr(:s)));
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-DEC-80 800 20
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10Or in pl/sql.
SQL> var c refcursor
SQL> begin
2 open :c for
3 select * from emp where ename in
4 (select upper(column_value) from table(tabstr(:s)));
5 end;
6 /
PL/SQL procedure successfully completed.
SQL> print c
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-DEC-80 800 20
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10 -
Hide or encrypt password in SQL/PLSQL code
Hi,
I need some help or suggestions to hide or encrypt database user password in SQL/PLSQL code. In our environment, we use a connect string with username/password for the JDBC connection. Our goal is to take out the password string and read it or pass it to the code on the fly.
Thanks,
SubrotoSo in the database somewhere you are storing username and password credentials? How do those credentials get sent to the Java application? Presumably, the Java application has to connect to the database, requiring a JDBC connection string, in order to query the table in order to get the username and password you've stored in the database.
Assuming there are two different JDBC connection strings-- one in the Java application that connects to the database and a second that is stored in the database and used later by the Java application, who do you want to protect the data from? Do you want to protect it from other database users? Or do you want to protect it from the Java developers? Or something else?
Justin -
WorkflowCA: TNS Connection String format not recognised
When I launch the scripts /wfinstall.csh, I get following error message:
[oracle@blmcqb install]$ Workflow Configuration Assistant - Linux
4
Parameter "wfdir" = /oracle/product/10.2.0/MPROD/wf
Parameter "orahome" = /oracle/product/10.2.0/MPROD
WorkflowCA: /oracle/product/10.2.0/MPROD/wf/install/workflow.log
WorkflowCA:
WorkflowCA: Workflow Configuration in progress...
WorkflowCA: Thu Mar 08 14:51:26 EST 2007
WorkflowCA:
WorkflowCA: Screen width -1024-, screen height -768-
WorkflowCA: TNS Connection String format not recognised
WorkflowCA:
WorkflowCA: Graphics User Interface mode
WorkflowCA:
WorkflowCA: Thu Mar 08 14:51:58 EST 2007
WorkflowCA: Invalid connect methodTWO_TASK=]
WorkflowCA: Terminating..
However, I can access the database without any problem:
[oracle@blmcqb install]$ tnsping OWBLAB
TNS Ping Utility for Linux: Version 10.2.0.3.0 - Production on 08-MAR-2007 15:01:24
Copyright (c) 1997, 2006, Oracle. All rights reserved.
Used parameter files:
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = blmcqb)(PORT = 1522))) (CONNECT_DATA = (SERVICE_NAME = OWBLAB)))
OK (0 msec)
[oracle@blmcqb install]$ sqlplus sys/rootpasswd@owblab as sysdba
SQL*Plus: Release 10.2.0.3.0 - Production on Thu Mar 8 15:02:05 2007
Copyright (c) 1982, 2006, Oracle. All Rights Reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bit Production
With the Partitioning, OLAP and Data Mining options
SQL> select name, open_mode from v$database;
NAME OPEN_MODE
OWBLAB READ WRITE
Does any expert has any idea?I got the same error. Then I gave whole string to ./wfinstall and then the Installation pass ok!
Like: (DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = rubik.my.domain)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = rubikdb.my.domain)))
Best Regards Antti -
Need advise on SQL,plsql developer career and future
Hi all,
I need all your advise in making an important decisions of my career path.I work in the IT field and have about total 4-5 years of work experience involving development and testing in a product based organization.
Presently-i have got chance since last 4-5 months to work with writing PLSQL code,SQL etc on a part basis. I am very much interested to continue my career path as a PLSQL developer.
But, unfortunately -in the total of my work experience-in the past 2-3 years-i worked with a internally developed DB query language(similar to SQL) and then from last few months with plsql. But this chance to work with PLSQL has been for less time and limited scope after which i will have to work on something different.
Ii want to fully take on my career in SQL,PLSQL as Database Developer.
Please advise me if my thinking seems logical and good and if I could do it. I have planned on applying for relevant SQL,PLSQL profile jobs.
Now, My serious worry and concern is I feel that since i have worked very less with PLSQL-so am low in confidence that I feel i wont be able to answer ,or tell or not knowledgeable enough to be able to clear the technical interviews for SQL,plsql development profile which would need at least some years of experience.
I have started studying and practsing PLSQL,sql by myself for from internet. So, can you all please advise me on how could i prepare myself for hard core technical interviews of SQL,PLSQL knowledge for about 2-3 years expertise.
I know its not much possible to be competent so much in the subject by just studying and practicing.Its easy as saying to study and get it by myself-but i want to try and will put my best for it.
Please help me with your inputs,all interview questions,hard ones-suggestions,links,any study materials, real time problems which i can try solving of SQL, PLSQL development.
Thanks AllHi,
A very good starting point is (in my opinion): [Steven Feuerstein PL/SQL Obsession|http://www.toadworld.com/Knowledge/DatabaseKnowledge/StevenFeuersteinsPLSQLObsession/tabid/153/Default.aspx]. Also the official site [PL/SQL Technology Center|http://www.oracle.com/technology/tech/pl_sql/index.html]
Regards, -
How to check the current time with a Stored time in string format
Hi All
I would like to compare the system time with an existing time values which is allready there in String format..
i mean i would like to check if the SysTime is inbetween 6:30 and 14:00
I accomplished this in Oracle ..
Select 'Y' from dual where to_date(to_char(sysdate,'HH24:MI '),'HH24:MI') between to_date('06:30','HH24:MI') and to_date('14:00','HH24:MI')
But instead of checking the DB each and every time , the perfomance would be better if we can do this in our java code..
Could some one provide me with a code to accomplish the above scenario..
Thanks in advance..,.,import java.util.Calendar;
Calendar rightNow = Calendar.getInstance(); // gets the current date and time to millisec
Calendar earlyTime = Calendar.getInstance().set(Calendar.HOUR_OF_DAY, 6).set(Calendar.MINUTE, 30);
Calendar lateTime = Calendar.getInstance().set(Calendar.HOUR_OF_DAY, 8).set(Calendar.MINUTE, 0);
if (rightNow.compareTo(earlyTime)> 0 && rightNow.compareTo(lateTime) < 0){
// do something
}Try this. -
How to read from a xml file(in String format) using a java program
hi friends
i have a string , which is xml format. i want read the values and display it.can any one suggest how to read a xml file of string format using a javaprogram
thanksfinal DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final InputStream documentStream = new ByteArrayInputStream(documentXMLSourceString.getBytes("utf-8"));
final Document document = db.parse(documentStream); -
Ok, I understand about numeric string formating (NumberFormat). But what I need help with is string formatting.
For example, I'm working on an app with fixed-length records. Let's take a name field. I need the string "John Doe" formatted to a 40-character field, right-justified. Can someone point me to a class or a URL with information on this.
Sorry for asking such an elementary question.Ok, I understand about numeric string formating
(NumberFormat). But what I need help with is string
formatting.
For example, I'm working on an app with fixed-length
records. Let's take a name field. I need the string
"John Doe" formatted to a 40-character field,
right-justified. Can someone point me to a class or a
URL with information on this.In the JDK I found nothing, but in the jakarta-Projekt of apache.org:
http://jakarta.apache.org/commons/lang.html
There is a class called StringUtils.
You only have to write:
String rightJustified = StringUtils.rightPad("John Doe", 40);
If you don't find something in the JDK look at Jakarta. They have a lot of useful stuff. -
Date formats for SQL statements used by recordset object
Hi,
Date formatting appears to be quite problematic for Business One. I did a forum search for date issues and I don't think I saw any of them with an "answered" status. I have an issue with formatting a date for the creation of an SQL statement that the DI sends to SQL Server 2005. I need to format a date so that the localization parameters don't matter for either the client machine or SQL Server's machine. We don't have a problem as long as our machines are localized as USA.
I have PL 22 and I have a form - ours - where I use the Today() function to fill a date field. So this is a date that is not entered by the user. The result of this function is consistent with the localization parameters on my machine. We have two other date fields on the form where the user must type in the date.
As a test, I changed my machine to the UK parameters. I then set up the language parameters of Business One for English(United Kingdom). I changed the date format specifications in Business One so that its format is dd/mm/yy. I then brought up the form and the field that is formatted by the above function arrived in the form's field as dd/mm/yy. I then typed in the two other dates in the same format and added the record to the database. The form's table is user-defined.
I dismissed the form then brought it back up loaded with the new record. The date that was entered by the function appeared in USA format (mm/dd/yy). The dates that were typed in appeared in the Business One format (dd/mm/yy). This of course is not consistent.
When I looked at what got into the database, the formats were the opposite. Weird! To make matters really confusing, I run an SQL statement within SQL Server Mgt Studio, and use the WHERE clause to filter on the date that was based on the function. It didnt matter what format I used for the WHERE clause, the record came up. Does anyone have any idea about how I can ensure that I always use the correct date format for SQL statements passed by Business One to SQL Server regardless of where in the world the application is being run?
Thanks,
MikeIan,
Here's what I'm concerned about: Im using the date in a WHERE clause.
Assume the date is Aug 3, 2007.
"SELECT * FROM Table WHERE StartDate > 8/3/2007"
OR
"SELECT * FROM Table WHERE StartDate > 3/8/2007"
If the client machine is set up as USA, the today function will provide the date as formatted in the first query. If the database server is setup as lets say the UK, I believe that SQL Server query parser will interpret the date as Mar 8, 2007.
If the client machine is set up as UK, the today function will provide the date as formatted in the second query. If the database server is setup as lets say USA, I believe that SQL Server query parser will also interpret the date as Mar 8, 2007.
In both cases it would be wrong.
I know I could use the DATEPART function to get the three parts and this will make the code indifferent to the localization specs of the client machine. I need to then be able to concatenate those date parts for the WHERE clause so that the localization specifications of the database server dont matter.
Thanks,
Mike
Maybe you are looking for
-
I currently had two apple ID's and I deleted the other on a whim a while back. Now whenever I need to update the iphoto or iMovie, it says to sign in into my deleted account, but I don't remember my old account's password nor the security questions.
-
USB audio device loses output connection
I use a MobilePRE USB interface and had no problems until recently. My iMac is set to never sleep but if I do not use the computer for a few hours the output from the MobilePre is gone.If I change to the driver to the internal headphone output on the
-
I'm afraid this post has nothing to do with Java, but I urgently require your help. My housemate has been working on coursework for his degree which is due in in 4 hours time. He has been using adobe photoshop on a mac. Unfortunatley, when he opened
-
Problem wth incomplete returns orders - Shipp pt and route are greyed out
Hi This is the problem with the incomplete return orders (v.02). All the subsequent documents are in complete process, but the returns order status is showing open status. This is because the user tried to remove the delivery block in returns order
-
Update Yes/No field in access table through oracle procedure
Hi, How to update Yes/No field in access table through oracle procedure. all other fields like AutoNumber, Text I can update it. Yes/No field how to update? Please, any one can help me? Thanks and Regards, Sudha.