String Generation in SQL
I have a table like this
with t
as
select 'aaa****aaa***aaa**' str
from dual
select *
from tI want an output like this.
aaa0000aaa000aaa01
aaa0000aaa000aaa02
aaa0000aaa000aaa10
aaa0000aaa000aaa11
aaa0000aaa000aaa19
aaa0000aaa000aaa99
aaa0000aaa001aaa00
aaa0000aaa001aaa01
and so on.Any help appreciated.
Thanks,
Karthick.
Karthick_Arp wrote:
oops forgot to mention the position and number of * can vary :(
the value could be like
aaa***aaa**aa*
aaaaa**aaaaa******aa***
aa**aaaa**
Edited by: Karthick_Arp on Dec 22, 2008 3:40 AMI am not sure how to interpret the above with relation to your later post:
Karthick_Arp wrote:
no it can be random...
I have gone this far.
SQL> with t
2 as
3 (
4 select 'aaa****aaa***aaa**' str
5 from dual
6 ),
7 num_count
8 as
9 (
10 select to_char(translate(lower(str),'*0123456789abcdefghijklmnopqrstuvwxyz','9')) len
11 from t
12 ),
13 num_gen
14 as
15 (
16 select trim(to_char(level,'0'||substr(len,2))) no
17 from t,num_count
18 connect by level <= len
19 )
20 select str, no
21 from t,num_gen
22 where rownum <=110
23 /
STR NO
aaa****aaa***aaa** 000000001
aaa****aaa***aaa** 000000002
aaa****aaa***aaa** 000000003
aaa****aaa***aaa** 000000004
aaa****aaa***aaa** 000000005
aaa****aaa***aaa** 000000006
aaa****aaa***aaa** 000000007
aaa****aaa***aaa** 000000008
aaa****aaa***aaa** 000000009
aaa****aaa***aaa** 000000010
aaa****aaa***aaa** 000000011
Are you saying sequence of a and * is random, but all rows in the table have the same structure? Or each row in the table can have random sequence of a and * ? I assumed the later, but it will work in both cases:
with t as (
select 'aaa***aaa**aa*' str from dual union all
select 'aaaaa**aaaaa******aa***' from dual union all
select 'aa**aaaa**' from dual
select str,
regexp_replace(source_char,pattern,replace_string) new_str
from (
select str,
',' || to_char(rn,'FM' || format_str) source_char,
pattern,
replace(replace(sys_connect_by_path(regexp_substr(str,'([^*]+)+?',1,level) || '\' || level,'!'),'!'),'*') replace_string
from (
select str,
rtrim(ltrim(regexp_replace(regexp_replace(str,'\*+','\d+') || 'a','a+','),('),')'),'(') pattern,
ltrim(regexp_replace(replace(str,'*','0') || 'a','a+',','),',') format_str,
row_number() over(order by length(replace(str,'a'))) rn,
length(replace(regexp_replace(str,'\*+','*'),'a')) asterisk_group_count
from t
where connect_by_isleaf = 1
connect by prior rn = rn
and prior dbms_random.random is not null
and level <= asterisk_group_count
SQL> with t as (
2 select 'aaa***aaa**aa*' str from dual union all
3 select 'aaaaa**aaaaa******aa***' from dual union all
4 select 'aa**aaaa**' from dual
5 )
6 select str,
7 regexp_replace(source_char,pattern,replace_string) new_str
8 from (
9 select str,
10 ',' || to_char(rn,'FM' || format_str) source_char,
11 pattern,
12 replace(replace(sys_connect_by_path(regexp_substr(str,'([^*]+)+?',1,level) || '\' || level,'!'),'!'),'*') replace_string
13 from (
14 select str,
15 rtrim(ltrim(regexp_replace(regexp_replace(str,'\*+','\d+') || 'a','a+','),('),')'),'(') pattern,
16 ltrim(regexp_replace(replace(str,'*','0') || 'a','a+',','),',') format_str,
17 row_number() over(order by length(replace(str,'a'))) rn,
18 length(replace(regexp_replace(str,'\*+','*'),'a')) asterisk_group_count
19 from t
20 )
21 where connect_by_isleaf = 1
22 connect by prior rn = rn
23 and prior dbms_random.random is not null
24 and level <= asterisk_group_count
25 )
26 /
STR NEW_STR
aa**aaaa** aa00aaaa01
aaa***aaa**aa* aaa000aaa00aa2
aaaaa**aaaaa******aa*** aaaaa00aaaaa000000aa003
SQL> SY.
Similar Messages
-
Parsing a string in PL/SQL?
I am parsing a string in PL/SQL and at a certain point(Length 45) of the string I would like to add a carriage return (Chr(10)), then continue with the string at that point and then again if the string is greater than Length 45 add a carriage return.
I program in Powerbuilder and have figured it out, but I have a problem when trying to add a carriage return at a certain point in the string in PL/SQL. There is the REPLACE(), but that will replace everything, but I only want to add it at that certain point of the string. With the PB function I can add the carriage return at a certain point, see code:
Li_pos = PosA( Ps_data, '*')
DO WHILE Li_pos > 0
ll_length = Li_pos - ll_old_pos
IF ll_length > 45 THEN
ll_old_pos = Li_pos
Ps_data = ReplaceA( Ps_data, Li_Pos, 1, ls_carriage_rtn) **This function gives me the ability to add a carriage return at a certain point in the string. **
Li_pos = PosA( Ps_data, '*', Li_pos + 1 + ls_carriage_rtn)
ELSE
Li_pos = PosA( Ps_data, '*', Li_pos + 1)
END IF
LOOP
I have incorporated the same logic in PL/SQL but I am looking for something similar to the ReplaceA function in PB, that will replace at a certain point in a string. I use an '*' as a placeholder and measure the length. Below is the PL/SQL code:
t_pos NUMBER;
t_old_pos NUMBER;
t_length NUMBER;
BEGIN
t_old_pos := 0;
t_pos := INSTR(in_model_list, '*');
WHILE t_pos > 0 LOOP
t_length := t_pos - t_old_pos; -- This looks at current position minus the old position, measures the length
IF t_length > 45 THEN
t_old_pos := t_pos;
*** add that carriage return
t_pos := INSTR(in_model_list, '*', t_pos + 1 + Chr(10)); -- get the new position
NULL;
ELSE
t_pos := INSTR(in_model_list, '*', t_pos + 1);
END IF;
NULL;
END LOOP;
Here is the data, what it looks like: William 112,* 500-A,* 500-U,* 520,* 560-A,* 560-E,* 680-E,* 680-F,* 680-V*
Any help would be much appreciated.
Thank you,
William
Edited by: William on Feb 28, 2012 6:56 AMFrank Kulash wrote:
[example]I played with your example and came to this:SQL> WITH my_string AS
2 (SELECT '1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'
3 AS mt
4 FROM DUAL)
5 , line_length AS
6 (SELECT 13 AS chars
7 FROM DUAL)
8 SELECT LISTAGG (REGEXP_SUBSTR (mt,'(.{'|| line_length.chars|| '})', 1, LEVEL),chr(10)) WITHIN GROUP (ORDER BY LEVEL)
9 ||chr(10)
10 ||substr(mt,-mod(LENGTH (mt),line_length.chars)) as wrapped_text
11 FROM my_string
12 CROSS JOIN line_length
13 CONNECT BY LEVEL < 1+LENGTH (mt) ;
WRAPPED_TEXT
1234567890123
4567890123456
7890123456789
0123456789012
3456789012345
6789012345678
9012345678901
2345678901234
5678901234567
8901234567890
1234567890123
WRAPPED_TEXT
4567890123456
7890
SQL>*[Edit]* annotated that this is 11g only...
Edited by: T.PD on 29.02.2012 21:17 -
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. -
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. -
Replacing a set of characters from a string in oracle sql query
I want to replace a set of characters ( ~ ! @ # $ % ^ * / \ + : ; | < > ? _ ,) from a STRING in sql
select 'TESTING ! ABC 123 #'
FROM DUAL;
What is the best way to do it? Please provide examples also.What is your expected output... The query I posted just removes them, it never replaces them with spaces..your string already has space.. if you want to remove space as well .. try this...
SELECT TRANSLATE ('TESTING ! ABC 123 #', '-~!@#$%^*/\+:;|<>?_, ', ' ') FROM DUAL;
Output:
--TESTINGABC123
Else post your expected output..
Cheers,
Manik. -
How to get numeric data from a string using t-sql
Hi All,
I have a table with 2 columns ID as Int and Message as nvarchar(max)
Create table Sample
ID int not null,
Message nvarchar(max) null,
CONSTRAINT [PK_ID_Msg] PRIMARY KEY CLUSTERED
ID asc
Insert statement:
INSERT INTO
Sample (ID, Message)
VALUES (1, 'X_YRS: 00 ; X_MONS: 18 ; X_DAYS: 000 ; Y_YRS: 00 ; Y_MONS: 16 ; Y_DAYS: 011 ; Z: 1 ; Z_DATE: 09/04/2014
INSERT INTO Sample (ID, Message) VALUES (2, 'X_YRS: 01 ; X_MONS: 15 ; X_DAYS: 010 ; Y_YRS: 00 ; Y_MONS: 18 ; Y_DAYS: 017
; Z: 1
; Z_DATE: 06/02/2012')
Data in the table looks like:
ID Message
1 X_YRS: 00 ; X_MONS: 18 ; X_DAYS: 000 ; Y_YRS: 00 ; Y_MONS: 16 ; Y_DAYS: 011 ; Z: 1 ; Z_DATE: 09/04/2014
2 X_YRS: 01 ; X_MONS: 15 ; X_DAYS: 010 ; Y_YRS: 00 ; Y_MONS: 18 ; Y_DAYS: 017 ; Z: 1 ; Z_DATE: 06/02/2012
Need out put as below, just with numeric data:
ID X-Column Y-Column
1 00 18 000 00 16 011
2 01 15 010 00 18 017
So, please I need t-SQL to get above output.
Thanks in advance.
RH
sql;With CTE
AS
SELECT s.ID,RTRIM(LTRIM(STUFF(Val,1,CHARINDEX(':',Val),''))) AS Val,RTRIM(LTRIM(LEFT(Val,CHARINDEX('_',Val+'_')-1))) AS Pattern,
--ROW_NUMBER() OVER (PARTITION BY LEFT(Val,CHARINDEX('_',Val+'_')-1) ORDER BY RTRIM(LTRIM(STUFF(Val,1,CHARINDEX(':',Val),'')))*1)
f.ID AS Seq
FROM Sample s
CROSS APPLY dbo.ParseValues(s.[Message],';')f
WHERE ISNUMERIC(RTRIM(LTRIM(STUFF(Val,1,CHARINDEX(':',Val),'')))+'0.0E0')=1
SELECT ID,
STUFF((SELECT ' ' + Val FROM CTE WHERE ID = c.ID AND Pattern = 'X' ORDER BY Seq FOR XML PATH('')),1,1,'') AS XCol,
STUFF((SELECT ' ' + Val FROM CTE WHERE ID = c.ID AND Pattern = 'Y' ORDER BY Seq FOR XML PATH('')),1,1,'') AS YCol,
STUFF((SELECT ' ' + Val FROM CTE WHERE ID = c.ID AND Pattern = 'Z' ORDER BY Seq FOR XML PATH('')),1,1,'') AS ZCol
FROM (SELECT DISTINCT ID FROM CTE)c
ParseValues can be found here
http://visakhm.blogspot.in/2010/02/parsing-delimited-string.html
Numeric check logic is as per below
http://visakhm.blogspot.in/2014/03/checking-for-integer-or-decimal-values.html
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
How to evaluate the dynamic condition string in PL/SQL ?
Hello, I am solving the issue of checking and validating the event table.
For Example, the event table namely "Contract_validated" contains some atts about a contract as follow:
CONTRACT_VALIDATED (SEQ_ID, CO_ID, VALID_T, CHANGE_KEY, ATT1, ATT1_FROM, ATT2, ATT2_FROM, REASON, CHANGE_KEY_ORIG, ATT1_ORIG, ATT2_ORIG)
In this table, the pairs (ATT1 and ATT1_FROM), (ATT2 and ATT2_FROM) must be compared to check whether the values are changed or not in the update event (change_key = U). If some records have change_key = U but the values does not change, I need to protocol and correct such records.
The table name and attributes list could be dynamic, and will be provided as parameters. Therefore, I use Dynamic PL/SQL to generate the code to test the conditions between the values between the pairs columns for detecting the invalid event. However, I am stucking in testing the condition phrases because I can not evaluate the condition string in the SELECT statement. I can not use IF because parts of this condition string take the value from a record and collection type. Anyone has the idea how to evaluate the condition in such case, please give me instructions or recommendations (it could be other alternatives to solve the problems)
Here is the code which generated from my Dynamic PL/SQL string, however, Oracle raise exception error at the EXECUTE IMMEDIATE v_sql command
SELECT 'x' FROM DUAL WHERE (NVL(v_rec.ATT1, NULL) <> NVL(v_rec.ATT1_FROM , NULL) OR (NVL(v_rec.ATT2, NULL) <> NVL(v_rec.ATT2_FROM , NULL))
E-0008: Unkown Exception raised in Loop. ORACLE:ORA-00904: "V_REC"."ATT2_FROM": invalid identifier
vo_traced_list has type Table of VARCHAR2(2000), storing the atts list of table (CONTRACT_VALIDATED), it has value already from other procedure invocation.
Here is the dynmic PL/SQL code generated dynamically depends on the table name, and attr list:
DECLARE v_rec CONTRACT_VALIDATED%ROWTYPE;
TYPE cv_type IS REF CURSOR;
v_rec_cv CV_TYPE;
v_cond VARCHAR2(4000);
cond BOOLEAN := FALSE;
v_exec VARCHAR2(1000);
v_default VARCHAR2(10):= 'NULL';
tk_val CONTRACT_VALIDATED.VALID_T%TYPE;
pk_val CONTRACT_VALIDATED.CO_ID%TYPE;
v_cnt NUMBER;
BEGIN
OPEN v_rec_cv FOR SELECT /*+ parallel(x,4) */ x.* FROM CONTRACT_VALIDATED x WHERE CHANGE_KEY = 'U' ORDER BY VALID_T;
FETCH v_rec_cv INTO v_rec;
IF v_rec_cv%NOTFOUND THEN
Add_Log('Event_Validating',v_user,v_event_validated,'INFO','I-0001: No-Procession needed');
ELSE
BEGIN
LOOP
pk_val := v_rec.co_id;
tk_val := v_rec.valid_t;
v_cnt := vo_traced_atts_list.COUNT;
v_cond := '(NVL(v_rec.'|| vo_traced_atts_list(1)||', ' || v_default || ') <> NVL(v_rec.' || vo_traced_atts_list(1)||'_FROM'
||' , ' || v_default || '))';
cond := (BOOLEAN) v_cond;
FOR v_i IN 2..v_cnt LOOP
BEGIN
v_cond := v_cond ||CHR(13)||CHR(10)||'OR (NVL(v_rec.'||vo_traced_atts_list(v_i)||', ' || v_default || ') <> NVL(v_rec.'||vo_traced_atts_list(v_i)||'_FROM'
||' , ' || v_default || '))';
END;
END LOOP;
v_exec := 'SELECT ''x'' FROM DUAL WHERE '||v_cond;
Add_Log('Event_Validating',v_user,v_event_validated,'INFO',v_exec);
EXECUTE IMMEDIATE v_exec;
/* Exception raised from here
E-0008: Unkown Exception raised in Loop. ORACLE:ORA-00904: "V_REC"."ATT2_FROM": invalid identifier
It seems that Oracle does not understand the dynamic reference v_rec.ATT2_FROM, v_rec.ATT2,... to test the condtion
IF SQL%ROWCOUNT = 0 THEN -- condition is false ==> traced attributes does not changed
-- update the REASON = 4 - not interested event
v_exec := 'UPDATE CONTRACT_VALIDATED SET REASON = 4 WHERE CO_ID = '||pk_val||' AND VALID_T = '||tk_val;
EXECUTE IMMEDIATE v_exec;
END IF;
FETCH v_rec_cv INTO v_rec;
EXIT WHEN v_rec_cv%NOTFOUND;
END LOOP;
EXCEPTION
WHEN OTHERS THEN
Add_Log('SCD_VALIDATION',v_user,v_event_validated,'ERROR','E-0008: Unkown Exception raised in Loop. ORACLE:'||SQLERRM);
RAISE ge_raise_error;
END;
END IF;
CLOSE v_rec_cv;
EXCEPTION
WHEN OTHERS THEN
Add_Log('SCD_VALIDATION',v_user,v_event_validated,'ERROR','E-0008: Unkown Exception raised in Loop. ORACLE:'||SQLERRM);
RAISE ge_raise_error;
END;Dear Andrew,
Thank you so much for your suggestions, however, I think it will be better to let me explain more about the situation.
I am working at Data Warehousing and Analysis part. The event tables are provided by other applications such as Customer OTLP system, Sales Management, etc. We therefore just have the results stored in the event tables (which could be wrong or inconsistency) and no way to force them to be valid by constraints. Before further processing the events , their records should be checked and overridden if possible, and that is the point I am trying to solve now.
The Event table names, their attributes list, data types, primary key, timestamp columns etc are dynamic and are provided via parameters. I would like to write a procedure which can check the invalid events (not only update, but also insert, delete), protocol them, and override them if possible before processing further. Because the table name, attribute lists, data type, etc are not known in advanced, to my best knowledge, the only choice is generating dynamic PL/SQL code although it could suck the performance. The code you have seen in my first question is the output from the follwoing procedure, where the i_att_list provides the atts list has been parsed from other procedure invocation, i_pk is the primary key, i_tk is the time key, i_table_name is the table name (which is Event_Validation in previous example). The stucking point I have met now is that I do not know how to test the condition to detect the different between column pairs (ATT1 and ATT1_FROM, ...). Using Select from dual is just a dummy select for testing the where condition which must be formed as a string by that way.
Thank you very much for your answer and looking forward to seeing your further recommendations or suggestions.
Regards,
Tho.
CREATE OR REPLACE PROCEDURE Update_Validation
( i_att_list enum_string, -- list of attributes
i_pk IN VARCHAR2, -- primary key column
i_tk IN VARCHAR2, -- time key column
i_table_name IN VARCHAR2 -- table_name - the columns format be checked
) AUTHID Current_User IS
TYPE LoopCurType IS REF CURSOR;
ln_parallel NUMBER := 4;
ge_raise_error EXCEPTION;
v_user VARCHAR2(100);
v_sql VARCHAR2(4000);
v_string VARCHAR2(4000);
v_crlf VARCHAR2(2) := CHR(13)||CHR(10);
BEGIN
SELECT sys_context('USERENV','current_schema') INTO v_user FROM DUAL;
v_sql:= 'SELECT /*+ parallel(x,'||ln_parallel||') */ x.* FROM ' ||i_table_name|| ' x '||
'WHERE CHANGE_KEY = ''U'''||
' order by '||i_tk;
v_string := 'DECLARE v_rec '||i_table_name||'%ROWTYPE;' ||v_crlf||
' TYPE cv_type IS REF CURSOR; ' ||v_crlf||
' v_rec_cv CV_TYPE; ' ||v_crlf||
' v_cond VARCHAR2(4000); ' ||v_crlf||
' v_exec VARCHAR2(100);' ||v_crlf||
' v_default VARCHAR2(10):= ''~~''; ' ||v_crlf||
' tk_val '||i_table_name||'.'||i_tk||'.%TYPE;'||v_crlf||
' pk_val '||i_table_name||'.'||i_pk||'.%TYPE;'||v_crlf||
' v_cnt NUMBER;' ||v_crlf||
'BEGIN ' ||v_crlf||
'OPEN v_rec_cv FOR ' ||v_sql ||';' ||v_crlf||
'FETCH v_rec_cv INTO v_rec;' ||v_crlf||
' IF v_rec_cv%NOTFOUND THEN ' ||v_crlf||
'Add_Log(''Event_Validating'',v_user,i_table_name,''INFO'',''I-0001: No-Procession needed'');'||v_crlf||
' ELSE ' ||v_crlf||
' BEGIN '||v_crlf||
' LOOP '||v_crlf||
'pk_val := v_rec.'||i_pk||';'||v_crlf||
'tk_val := v_rec.'||i_tk||';'||v_crlf||
'v_cnt := i_att_list.COUNT;' ||v_crlf||
'v_cond := ''NVL(v_rec.''|| i_att_list(1)||'', '' || v_default || '') <> NVL(v_rec.'' || i_att_list(1)||''_FROM'''||v_crlf||
'||'' , '' || v_default || '')'';'||v_crlf||
'FOR v_i IN 2..v_cnt LOOP'||v_crlf||
'BEGIN'||v_crlf||
'v_cond := v_cond ||CHR(13)||CHR(10)||''OR NVL(v_rec.''||i_att_list(v_i)||''), <> NVL(v_rec.''||i_att_list(v_i)||''_FROM'''||v_crlf||
'||'' , '' || v_default || '')'';'||v_crlf||
'END;'||v_crlf||
'END LOOP;'||v_crlf||
'v_exec := ''SELECT ''x'' FROM DUAL WHERE ''||v_cond;'||v_crlf||
'EXECUTE IMMEDIATE v_exec;'||v_crlf||
'IF SQL%ROWCOUNT = 0 THEN -- condition is false ==> traced attributes does not changed'||v_crlf||
'-- update the REASON = 4 - not interested event'||v_crlf||
'UPDATE '||i_table_name||' SET REASON = 4 WHERE '||i_pk||' = '||v_tk||' AND '||i_tk||' = '||tk_val||';'||v_crlf||
'END IF;'||v_crlf||
'FETCH v_rec_cv INTO v_rec;' ||v_crlf||
'EXIT WHEN v_rec_cv%NOTFOUND;'||v_crlf||
' END LOOP;'||v_crlf||
'EXCEPTION' ||v_crlf||
'WHEN OTHERS THEN'||v_crlf||
'Add_Log(''SCD_VALIDATION'',v_user,i_table_name,''ERROR'',''E-0008: Unkown Exception raised in Loop. ORACLE:''||SQLERRM);'||v_crlf||
'RAISE ge_raise_error;'||v_crlf||
'END;'||v_crlf||
'END IF;'|| v_crlf||
'Close v_rec_cv;'||v_crlf||
'EXCEPTION' ||v_crlf||
'WHEN OTHERS THEN'||v_crlf||
'Add_Log(''SCD_VALIDATION'',v_user,i_table_name,''ERROR'',''E-0008: Unkown Exception raised in Loop. ORACLE:''||SQLERRM);'||v_crlf||
'RAISE ge_raise_error;'||v_crlf||
'END;';
Add_Log('SCD_UPDATE_VALIDATION',v_user,i_table_name,'INFO','I-0006: Update Validation : '||v_string);
EXECUTE IMMEDIATE v_string;
EXCEPTION
WHEN OTHERS THEN
Add_Log('SCD_VALIDATION',v_user,i_table_name,'ERROR','E-0008: Unkown Exception raised in Loop. ORACLE:'||SQLERRM);
END Update_Validation; -
How to escape a single quotes from a string of dynamic sql clause?
if a single quotes exist in a dynamic sql clause for a string,
like
v_string :='select tname from tab where tabtype='table'',
there tabtype='table' will conflict with the single quote ahead.
could somebody tell me how to escape this single quotes?
thanks for your tips,
frederickfredrick,
To represent one single quotation mark within a literal, enter two single quotation marks. For example :
v_string :='select tname from tab where tabtype=''table'''
Regards,
Srinivas -
Error while passing parameter(quoted string parameter ) to sql script
Hi all,
I have a master script insert_attribute_single.sql which takes 6 parameter. when i am using in sql prompt
SQL>@@INSERT_ATTRIBUTE_SINGLE.SQL 'LEED PROJECT START DATE' 7 'N' 27265185 '7'22'008' NULL;
then it is giving error for the 5th parameter. and i need to pass 5th parameter '7'22'008' in this.
in the master script it is giving error - ORA-06550 here.
dbms_output.put_line('Processing attribute : &1 Project : &4 Char value : &5 Numeric Value : &6 ' ) ;
can you please help me to resolve this with single quotes in string.
Thanks in advance.
regards
shyam~Here is my sql file:
declare
a_Var VARCHAR2(10) := '&1';
begin
dbms_output.put_line(a_var||','||'&2');
end;
/Here is how I am calling the sql file with parameter values containing quotes in itself:
SQL> @@d:\a.sql '12''''23''''23' '123'
old 2: a_Var VARCHAR2(10) := '&1';
new 2: a_Var VARCHAR2(10) := '12''23''23';
old 4: dbms_output.put_line(a_var||','||'&2');
new 4: dbms_output.put_line(a_var||','||'123');
12'23'23,123
PL/SQL procedure successfully completed.
SQL> -
Passing a string into an SQL query IN statement
Hello,
I need to connect to a database to pull some data to dynamically create a form based on the data I pull back. My SQL query works fine when I manually run it through a SQL client tool, but when I try to pass it through my workflow I'm having trouble with passing my string into the IN part of the statement. So if for example my SQL query is:
SELECT Field1, Field2, Field3 FROM Table1 WHERE Field4 IN (?)
I have a process variable that has the string I'm trying to pass into the ?, but I don't seem to be able to get the query to run. I have tried setting up my query to run as a Parameterized Query (passing my string process variable into the ?), and by setting the query up through xPath (where I am calling my process variable with an xPath declaration), but am not having any luck.
The process variable I am trying to pass is formatted such that I'm passing 'Value1','Value2','Value3' but I can reformat this string if need be. Even with using test data I can't get the query to return anything. For test data I have tried: 'Value1','Value2','Value3' ; Value1','Value2','Value3 ; Value1,Value2,Value3 but the query never returns any data. I can't seem to see how to format the string to pass into the query. The Query will work with a single Value in the test data, but as soon as I try to pass multiple values within the string it fails. Any suggestions?The problem looks to be a limit on what I can pass into the SQL query component. My string is coming from data returned from another database. I take the xml output from that database call, pass it through a set variable component to remove my xml tags from the string, and then format the string in a script component (I have to do it this way because of the way the data coming out of my first database call). I've put in loggers, and can see that the string I'm passing into my query that is giving me problems, is formatted the same way as if I were to use the concat function Scott listed above. It looks like there is a limitation on what can be passed in my variable. I have tried creating my entire SQL query statement in a set variable component, and then just calling the process variable that holds that statement, but there is a character limit of 128 character for what can be passed in a variable through xpath in the SQL query component.
The next thing I tried was changing my SQL where clause. Instead of passing my variable directly into the IN statement I set up a PATINDEX('%:'+countyname+ ':%', ?) > 0 call to check for the values in my database call. As you can see I took out the "," that I was passing as part of my string, thinking that the SQL component was getting confused by them, and placed ":" characters around my values being passed in my string variable. No matter what I try to do though I'm not able to get the query to run. The component looks like it is taking my string, and is seeing the whole thing as a string instead of passing it as individual values within a string.
I think I'm getting close, but I keep getting a Content not allowed in prolog exception in the server logs. -
Substitution strings in chart sql query
Hi Guys,
I am creating line charts and bar charts based on a query in HTML DB 1.5. I am using substitution strings in the query. Though I can use substitution strings in the line chart, I cannot do it in the bar chart. I am using almost the same sql query in both line and bar charts.
The sql query in line chart is
SELECT null, TO_CHAR(t1.extract_date, 'W-MON-YYYY') extractdate,
MIN_OF_AVERAGES(AVG(&P40_METRICS.),:P40_REGION_LIST,:P40_SUBREGION_LIST,NULL,:P40_METRICS,'ind') orgid
FROM ind t1,geography t2
WHERE t1.country_id = t2.country_id(+)
AND t2.region_name like
DECODE(:P40_REGION_LIST,'ALL REGIONS','%',:P40_REGION_LIST)
AND t2.subregion_name like
NVL(:P40_SUBREGION_LIST,'%')
GROUP BY TO_CHAR(extract_date, 'W-MON-YYYY')
order by to_date(extractdate,'DD-MON-YY')
The sql query in bar chart is
SELECT null, TO_CHAR(t1.extract_date, 'W-MON-YYYY') extractdate,AVG(&P40_METRICS.) orgid
FROM ind t1,geography t2
WHERE t1.country_id = t2.country_id(+)
AND t2.region_name like
DECODE(:P40_REGION_LIST,'ALL REGIONS','%',:P40_REGION_LIST)
AND t2.subregion_name like
NVL(:P40_SUBREGION_LIST,'%')
GROUP BY TO_CHAR(extract_date, 'W-MON-YYYY')
order by to_date(extractdate,'DD-MON-YY')
The min_of_averages function in the line chart query is some function I am calling. Even if I cut-paste the line chart query in the bar chart I get the error.
The substitution string which is giving the problem is "&P40_METRICS."
The error I am getting is
Query cannot be parsed, please check the syntax of your query. (ORA-00909: invalid number of arguments)
The only difference I see is that line chart query is inside a series and bar chart is not, does this make a difference??? Or is it because I am using the substitution string in choosing the column??? Please help!!!!
Thanks,
SwaroopSwaroop,
You might be using an HTML bar chart and an SVG line chart, I can't tell, but their implementations differ. You won't be able to use a substitution string to replace a column name in the query in the situation you found, you'd have to figure out a way to construct the query string before it gets executed and I'm not sure the chart pages will let you do that.
Scott -
Mappings code generation : regular SQL / cursor PL/SQL
Hi,
When designing mappings, I fear that code generation can be potentially dangerous, because OWB automatically chooses the best method to generate the code (regular SQL or PL/SQL).
I am looking for some examples where code generation for a mapping:
- gives a regular SQL statement
- gives a cursor-based PL/SQL
- a small change in a mapping makes a regular SQL mapping to be transformed in a cursor-based PL/SQL
Thank you
Alexandre
Message was edited by:
Alexandre AbricI have not said that different modes executes at the same way what the use to have different options if they actually mean the same, right? I have said that they produced the same result i.e. if you expect the mapping to insert 1000 rows from the source to the target it will be done no matter which operation mode you choose.
But by different ways. To keep it simple lets say that:
set base mode will result in:
insert into target ( )
select from source;
row based will result in:
begin
for a in (select * from source) loop
insert into target
end loop;
end;
Now lets assume that 5 rows from those 1000 you are going to insert, will break some NOT NULL constraint at the target.
If you choose Set-base mode entire insert from select will fail resulting no rows is inserted into target. Audit trail will contain message like constraint violated and thats it. You will have to find bad records by yourself.
If you choose Row-base mode 995 rows will be inserted (depending on mapping configuration) into the target and 5 will be listed in audit trail with the same constraint violated message.
Thats why default operating mode is Set based fail over to Row based. That means OWB will try to execute mapping in the fastest way set based, but if it fail, it will try again to accomplish the task by running in row base mode, providing complete audit trail fro bad rows. -
Trying to convert String to java.sql.Date
I need to convert a String (in the format "yyyy-mm-dd") to java.sql.Date
It was suggested I use the following,
SimpleDateFormat formater = new SimpleDateFormat("yyyy-mm-dd");
Date result = formater.parse(dbirth.getText());
However, It seem to produce a java.util.Date
Error: found java.util.Date
Required : java.sql.Date
Can anyone help?
Thanks, MarikaI need to convert a String (in the format
"yyyy-mm-dd") to java.sql.Date
It was suggested I use the following,
SimpleDateFormat formater = new
SimpleDateFormat("yyyy-mm-dd");
Date result = formater.parse(dbirth.getText());
However, It seem to produce a java.util.Date
Error: found java.util.Date
Required : java.sql.Date
Can anyone help?
Thanks, Marika SimpleDateFormat formater = new SimpleDateFormat("yyyy-mm-dd");
java.util.Date parsedDate = formater.parse(dbirth.getText());
java.sql.Date result = new java.sql.Date(parsedDate.getTime()); -
How to Compare two strings in PL/SQL
Hi All,
I need to compare two strings whether they are equal or not in PL/SQL.Is there any function to comparing the strings.Yes, the = sign.
Are you after something like:
IF v_string1 = v_string2 THEN
ELSE
END IF;?
Edited by: Boneist on 27-Aug-2009 11:41 -
Apostrophe in a String bombs a SQL insert
I am having an issue with a Customer String parameter that is being used in a SQL INSERT. The customer name may from time to time have an apostrophe in it that causes our SQL INSERT to bomb on a missing comma error. I have tried to do this two separate ways:
1)
String query = "INSERT into CUSTOMER VALUES(" + account[0].custAcctNbr + ",'" + account[0].companyNm + "'," +
"'IN',null," + salesPerson[0].salespersonID + "," + "null,null,null,null,null," +
"null,null,null,null,null,null,null,null,null)";
This works until an apostrophe is in the companyNm varaiable.
2)
PreparedStatement insertCustomer = bcc_conn_cust.prepareStatement(
"INSERT into CUSTOMER VALUES(?,?,?,null,?,null,null,null,null,null,null,null,null,null,null,null,null,null,null");
insertCustomer.setInt(1,Integer.parseInt(account[0].custAcctNbr));
insertCustomer.setString(2,account[0].companyNm);
insertCustomer.setString(3,"IN");
insertCustomer.setInt(4,salesPerson[0].salespersonID);
insertCustomer.executeUpdate();
This also works when there is no apostrophe. However both bomb when it is present. Is there anyway to get around this, short of parsing a company name every single time we insert a new customer?Do you have any idea why this is not working? yes, whatever driver you are using isn't implementing this properly.
variable I am using is a String variable, that has a
value of Bates' Brownies. According to all I read, it
seems I have used the Prepared Statement correctly but
it is giving me that missing comma error. I would
really rather not have to search every single company
name as it is entered.well unless you can either find another driver or fix the one you've
got i can't see what else you can do...
here is some code to help you along with that.
private String replaceQuotes(String toReplace){
StringBuffer buff = new StringBuffer(toReplace);
for(int i=0;i<buff.length();i++){
if(buff.charAt(i)=='\''){
buff.insert(i,'\'');
i++;
return buff.toString();
Maybe you are looking for
-
Mac wont mount disk images, and fails to auto detect some usb devices.
for some reason, all of a sudden, my mac won't mount disks. even disks I know in the past have worked. also, it wont auto detect some external devices. especially jump drives and hard drives and audio interfaces. It has to be rebooted with the the de
-
I am running lion now and I am not able to safe my emails to the computer with the attachments. what's wrong?
-
Repair Disk Permissions: is it a safe operation ?
Hello, I'm preparing for the 101 course and, reading about the Verify/Repair disk permissions utility, I wanted to test it on my mac. I launched the verification on it and I see "lot" of unexpected entries (see below): Verifying permissions for “Maci
-
Need to add new field in Rfx Line Item Page
Hi I want to add an new extended field in RFX line item page ( Rfx-> line item tab -> click on the pencil icon of any line items ) can anyone help me ? Regards Sudipta
-
Remove Special Character "/" from file name
I'm trying to upload a PDF located on my desktop to a server that won't accept special characters, and the mac path is by default ~/desktop/file ... all those forward slashes read as "special characters" and the file is rejected. I moved the file as