How to split a string using sql
Hi All,
I've to write a query where I need to split a string, how this can be done? So let's say a column has value as 1,2,3,4,5 and I want to split this string and output it as:
1
2
3
4
5
Please advise.
Lots of articles:
Snap this user defined function too:
CREATE FUNCTION [dbo].[ufn_SplitString_Separator](@InputStr VARCHAR(MAX), @Separator VARCHAR(1))
RETURNS @tmpTable TABLE (OutputStr VARCHAR(MAX))
AS BEGIN
DECLARE @TmpPOS integer
SET @TmpPOS = CHARINDEX(@Separator,@InputStr)
WHILE @TmpPos > 0 BEGIN
IF @TmpPos > 0 BEGIN
INSERT INTO @tmpTable VALUES (LTRIM(RTRIM(SUBSTRING(@InputStr,1,@TmpPos-1))))
SET @InputStr = SUBSTRING(@InputStr, @TmpPOS + 1, LEN(@InputStr) - @TmpPos)
SET @TmpPOS = CHARINDEX(@Separator,@InputStr)
END ELSE BEGIN
INSERT INTO @tmpTable VALUES (LTRIM(RTRIM(@InputStr)))
SET @TmpPos = 0
END
END
IF LEN(@InputStr) > 0 BEGIN
INSERT INTO @tmpTable VALUES (LTRIM(RTRIM(@InputStr)))
END
RETURN
END
GO
And you can use like this:
SELECT * FROM DBO.[ufn_SplitString_Separator]('1,2,3,4,5',',')
"If there's nothing wrong with me, maybe there's something wrong with the universe!"
Similar Messages
-
Need Help in Splitting a String Using SQL QUERY
Hi,
I need help in splitting a string using a SQL Query:
String IS:
AFTER PAINT.ACOUSTICAL.1..9'' MEMBRAIN'I would like to seperate this string into multiple lines using the delimeter .(dot)
Sample Output should look like:
SNO STRING
1 AFTER PAINT
2 ACOUSTICAL
3 1
4
5 9" MEMBRAIN
{code}
FYI i am using Oracle 9.2There's this as well:
with x as ( --generating sample data:
select 'AFTER PAINT.ACOUSTICAL.1..9" MEMBRAIN' str from dual union all
select 'BEFORE PAINT.ELECTRIC.2..45 caliber MEMBRAIN' str from dual)
select str,
row_number() over (partition by str order by rownum) s_no,
cast(dbms_xmlgen.convert(t.column_value.extract('//text()').getstringval(),1) as varchar2(100)) res
from x,
table(xmlsequence(xmltype('<x><x>' || replace(str,'.','</x><x>') || '</x></x>').extract('//x/*'))) t;
STR S_NO RES
AFTER PAINT.ACOUSTICAL.1..9" MEMBRAIN 1 AFTER PAINT
AFTER PAINT.ACOUSTICAL.1..9" MEMBRAIN 2 ACOUSTICAL
AFTER PAINT.ACOUSTICAL.1..9" MEMBRAIN 3 1
AFTER PAINT.ACOUSTICAL.1..9" MEMBRAIN 4
AFTER PAINT.ACOUSTICAL.1..9" MEMBRAIN 5 9" MEMBRAIN
BEFORE PAINT.ELECTRIC.2..45 caliber MEMBRAIN 1 BEFORE PAINT
BEFORE PAINT.ELECTRIC.2..45 caliber MEMBRAIN 2 ELECTRIC
BEFORE PAINT.ELECTRIC.2..45 caliber MEMBRAIN 3 2
BEFORE PAINT.ELECTRIC.2..45 caliber MEMBRAIN 4
BEFORE PAINT.ELECTRIC.2..45 caliber MEMBRAIN 5 45 caliber MEMBRAIN
{code} -
How to split a string using IndexOf?
How would you split a string using indexOf and not using the .split method?
Any help is appreciated :D
Message was edited by:
billiejoewould it be better to use the first or the second?
int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
I think the second would be helpful. so how do i read it? -
How to Split the string using Substr and instr using loop condition
Hi every body,
I have below requirement.
I need to split the string and append with single quotes('') followed by , (comma) and reassign entire values into another variable. so that i can use it where clause of update statement
for example I am reciveing value as follows
ALN varchar2(2000):=(12ERE-3MT-4Y,4IT-5O-SD,OP-K5-456,P04-SFS9-098,90P-SSF-334,3434-KJ4-O28,AS3-SFS0-J33,989-3KL-3434);
Note: In the above variable i see 8 transactions, where as in real scenario i donot how many transaction i may recive.
after modification i need above transactions should in below format
ALTR Varchar2(2000):=('12ERE-3MT-4Y','4IT-5O-SD','OP-K5-456','P04-SFS9-098','90P-SSF-334','3434-KJ4-O28','AS3-SFS0-J33','989-3KL-3434');
kindly help how to use substr and instr in normal loop or for loop or while loop while modifying the above transactions.
Please help me to sort out this issue.
Many Thanks.
Edited by: user627525 on Dec 15, 2011 11:49 AMTry this - may not be the best way but...:
create or replace type myTableType as table of varchar2(255)
declare
v_array mytabletype;
v_new_str varchar2(4000);
function str2tbl
(p_str in varchar2,
p_delim in varchar2 default '.')
return myTableType
as
l_str long default p_str || p_delim;
l_n number;
l_data myTableType := myTabletype();
begin
loop
l_n := instr( l_str, p_delim );
exit when (nvl(l_n,0) = 0);
l_data.extend;
l_data( l_data.count ) := ltrim(rtrim(substr(l_str,1,l_n-1)));
l_str := substr( l_str, l_n+length(p_delim) );
end loop;
return l_data;
end;
begin
v_array := str2tbl ('12ERE-3MT-4Y,4IT-5O-SD,OP-K5-456,P04-SFS9-098,90P-SSF-334,3434-KJ4-O28,AS3-SFS0-J33,989-3KL-3434', ',');
FOR i IN 1 .. v_array.COUNT LOOP
v_new_str := v_new_str || ''''||v_array(i)||'''' || ',';
END LOOP;
dbms_output.put_line(RTRIM(v_new_str, ','));
end;
OUTPUT:
=======
'12ERE-3MT-4Y','4IT-5O-SD','OP-K5-456','P04-SFS9-098','90P-SSF-334','3434-KJ4-O28','AS3-SFS0-J33','989-3KL-3434'HTH
Edited by: user130038 on Dec 15, 2011 12:11 PM -
How to "split" a string using API 1.3?
Hi everyone,
I'm needing to split strings at the slash "/" character.
Unfortunately, we're using API 1.3, and according to the API, "split" isn't available until 1.4.
I'm looking for suggestions, help, examples, or alternatives.
Thanks!How about StringTokenizer?
-
How do count how many 'A' s in this string using sql stmt?
hi all,
i have a string like 'AAAAARAMAAAAKRISHNAAAA'.
in this ,i want to find out how many 'A's .
how do find out this using select stmt.(length(s) - nvl(length(replace(s, 'A')), 0)) / length('A')but consider (by modifying the question slightly to "how do count how many 'AA' s in this string using sql stmt? ")
SQL> select (length('AAAAARAMAAAAKRISHNAAAA') - nvl(length(replace('AAAAARAMAAAAKRISHNAAAA', 'AA')), 0)) / length('AA') x from dual
X
6
1 row selected.couldn't I argue that the result should be 10 as e.g. in
SQL> select * from xmltable('let $str := "AAAAARAMAAAAKRISHNAAAA"
let $search := "AA"
for $i in 1 to string-length($str)
where substring($str, $i, string-length($search)) = $search
return substring($str, $i, string-length($search))' columns x varchar2(10) path '.')
X
AA
AA
AA
AA
AA
AA
AA
AA
AA
AA
10 rows selected.Matter of definition I suppose .... ;)
btw. regexp_count also yields 6:
SQL> select regexp_count('AAAAARAMAAAAKRISHNAAAA', 'AA') x from dual
X
6
1 row selected. -
How to split the string by datetime in sql
Hi,
How to split the string by datetime in sql, I've a table with comments column stores comments by datetime, while selecting I want to split and show as in rows by each jobref.
can anyone help me in this please.
Thanks,declare @callcentre table (comments varchar(max),lbiref varchar(200))
insert into @callcentre
select '(28/10/2014 14:56:14) xyz ..... call logged (28/10/2014 14:56:58) xyz ..... call updated (28/10/2014 14:57:41)xyz ..... call updated','Vi2910201'
insert into @callcentre
select '(29/10/2014 14:56:14) xyz ..... call logged (29/10/2014 14:56:58) xyz ..... call updated (29/10/2014 14:57:41)xyz ..... call updated','Vi2910202'
insert into @callcentre
select '(30/10/2014 14:56:14) xyz ..... call logged (30/10/2014 14:56:58) xyz ..... call updated
output:
1) 28/10/2014 14:56:14, (28/10/2014 14:56:14) xyz ..... call logged ,'Vi2910201'
2) 28/10/2014 14:56:58 ,(28/10/2014 14:56:58) xyz ..... call updated ,'Vi2910201'
3) 28/10/2014 14:57:41, (28/10/2014 14:57:41)xyz ..... call updated,'Vi2910201'
4) 28/10/2014 14:56:14, (28/10/2014 14:56:14) xyz ..... call logged ,'Vi2910202'
5) 28/10/2014 14:56:58 ,(28/10/2014 14:56:58) xyz ..... call updated ,'Vi2910202'
6) 28/10/2014 14:57:41, (28/10/2014 14:57:41)xyz ..... call updated,'Vi2910202'
7) 28/10/2014 14:56:14, (28/10/2014 14:56:14) xyz ..... call logged ,'Vi2910203'
8) 28/10/2014 14:56:58 ,(28/10/2014 14:56:58) xyz ..... call updated ,'Vi2910203'
Thanks,
See this illustration
declare @callcentre table (comments varchar(max),lbiref varchar(200))
insert into @callcentre
select '(28/10/2014 14:56:14) xyz ..... call logged (28/10/2014 14:56:58) xyz ..... call updated (28/10/2014 14:57:41)xyz ..... call updated','Vi2910201'
insert into @callcentre
select '(29/10/2014 14:56:14) xyz ..... call logged (29/10/2014 14:56:58) xyz ..... call updated (29/10/2014 14:57:41)xyz ..... call updated','Vi2910202'
insert into @callcentre
select '(30/10/2014 14:56:14) xyz ..... call logged (30/10/2014 14:56:58) xyz ..... call updated','Vi2910203'
SELECT LEFT(p.u.value('.[1]','varchar(max)'),CHARINDEX(')',p.u.value('.[1]','varchar(max)'))-1) AS [Date],
'(' + p.u.value('.[1]','varchar(max)') AS comments,
lbiref
FROM
SELECT lbiref,CAST('<Root>' + STUFF(REPLACE(comments,'(','</Data><Data>'),1,7,'') + '</Data></Root>' AS XML) AS x
FROM @callcentre c
)t
CROSS APPLY x.nodes('/Root/Data')p(u)
and the output
Date comments lbiref
28/10/2014 14:56:14 (28/10/2014 14:56:14) xyz ..... call logged Vi2910201
28/10/2014 14:56:58 (28/10/2014 14:56:58) xyz ..... call updated Vi2910201
28/10/2014 14:57:41 (28/10/2014 14:57:41)xyz ..... call updated Vi2910201
29/10/2014 14:56:14 (29/10/2014 14:56:14) xyz ..... call logged Vi2910202
29/10/2014 14:56:58 (29/10/2014 14:56:58) xyz ..... call updated Vi2910202
29/10/2014 14:57:41 (29/10/2014 14:57:41)xyz ..... call updated Vi2910202
30/10/2014 14:56:14 (30/10/2014 14:56:14) xyz ..... call logged Vi2910203
30/10/2014 14:56:58 (30/10/2014 14:56:58) xyz ..... call updated Vi2910203
Please Mark This As Answer if it solved your issue
Please Mark This As Helpful if it helps to solve your issue
Visakh
My MSDN Page
My Personal Blog
My Facebook Page -
How To Split the String for "."
Hi Friends
I am Using Following Code to Split one String.
String str = "Jeetendra.choudhary";
String[] sp_str = str.split(".");
wdComponentApi.getMessageManager.reportSuccess(str[0]);
wdComponentApi.getMessageManager.reportSuccess(str[1]);
but its throwing null pointer exception.
when i am using following code its working fine.
String str = "Jeetendra/choudhary";
String[] sp_str = str.split("/");
wdComponentApi.getMessageManager.reportSuccess(str[0]);
wdComponentApi.getMessageManager.reportSuccess(str[1]);
what may be the issue and how to split the string with "." ?
Thanks & Regards
Jeetendra"." is a special character.
Use
str.split("\\.");
Regards
Benjamin
Edited by: Benjamin Hansen on Dec 29, 2009 7:52 AM -
How to get this output using sql query?
Hi,
How to get this output using sql query?
Sno Name Age ADD Result
1 Anil 23 delhi Pass
2 Shruti 25 bangalor Pass
3 Arun 21 delhi fail
4 Sonu 23 pune Pass
5 Roji 26 hydrabad fail
6 Anil 28 delhi pass
Output
Sno Name Age ADD Result
1 Anil 23 delhi pass
28 delhi passHi Vamshi,
Your query is not pretty clear.
write the select query using Name = 'ANIL' in where condition and display the ouput using Control-break statements.
Regards,
Kannan -
How to hide repeated details using SQL Query?
How to hide repeated details using SQL Query?
For Ex:
------------------------+
DEPTNO| ENAME | JOB |
------|-------| --------|
10 | JAMES | MANAGER |
10 | BLAKE | CLERK |
10 | FORD | SALESMAN|
20 | SCOTT | MANAGER |
20 | ADAMS | CLERK |
20 | KING | SALESMAN|
------------------------+
How we can display the above details in the following way?
------------------------+
DEPTNO| ENAME | JOB |
------|-------| --------|
10 | JAMES | MANAGER |
| BLAKE | CLERK |
| FORD | SALESMAN|
20 | SCOTT | MANAGER |
| ADAMS | CLERK |
| KING | SALESMAN|
------------------------+
Thanks AdvanceHi,
you can use BREAK ON DEPTNO in SQL*Plus or use LAG.
SQL> ed
Wrote file afiedt.buf
1 select nullif(department_id
2 , lag(department_id) over (partition by department_id order by last_name)
3 ) dept_id
4 , last_name, job_id
5* from employees where department_id in (30,50) and rownum <=10
SQL> /
DEPT_ID LAST_NAME JOB_ID
30 Baida PU_CLERK
Colmenares PU_CLERK
Himuro PU_CLERK
Khoo PU_CLERK
Raphaely PU_MAN
Tobias PU_CLERK
50 Fripp ST_MAN
Kaufling ST_MAN
Vollman ST_MAN
Weiss ST_MAN
10 rows selected. -
How to view alerlog contents using SQL?
How to view alertlog contents using SQL?
Hi,
Why don't you use the OEM Database Console ?? Now, in order to view the contents of the alert log file using a SELECT statement, you need to create a external table:
create or replace
directory background_dump_dest_dir
as '<your_oracle_home>/bdump';
CREATE table alert_log_external
(line varchar2(4000) )
ORGANIZATION EXTERNAL
(TYPE oracle_loader
DEFAULT DIRECTORY background_dump_dest_dir
ACCESS PARAMETERS (
RECORDS DELIMITED BY newline
nobadfile
nologfile
nodiscardfile
FIELDS TERMINATED BY '#$~=ui$X'
MISSING FIELD VALUES ARE NULL
(line)
LOCATION ('alert_<sid_of your_database>.log') )
REJECT LIMIT UNLIMITED;Cheers -
How to split a string for 2 different matching patterns?
hey guys
i'm trying to split a string, using .split(regular expression), if two different pattern matches but i don't know the exact syntax for it. I want to split the string from letters and punctuations.
This is what i'm doing, obviously it's not working, i'm not too sure if syntax are correct.
String inputDigit [] = input.split("([a-zA-Z]) (\\p{Punct})");Please help me with this, thank you!Can you describe in more detail what you're trying to
accomplish?ok, basically if you have a string which consists of letters, digits and punctuations. All i'm trying to do or want to do is store all digist within that string into an array. Therefore, i'm using split method to split the string wherever you find a letter or a punctuation. But i don't know what is syntax for using two different patterns at the same time.
// For example if you have a string "Eeyore 61 2.986PoohPiglet007Kanga-23"
// i only want: 61 2 986 007 23. I know i can use substring // but that would be a slightly long process -
Split a string using Match Pattern function
I am trying to split a response string from a climate chamber into different parts. The string goes something like this: 0030.0\s0034.6\s0080.0\s0083.4. I am using the match pattern function to split the string using \s as the search string. But it is not splitting the string as required. If I use only \ , its working fine. Can anyone please suggest why \s is not being recognised as a part of the input string?
Subhro.
Solved!
Go to Solution.Is the string you show in normal display mode or in \ codes display mode?
Anyway, if you need to match a '\' character you'll have to mask it using \, so the match string would be '\\s' to match '\s'.
Alternatively you could use spreadsheet string to array with the correct delimiter. For the data you show this would work perfectly. -
how to split this string (char1)char2(char3)char4 into (char1)char2 , (char3)char4?
String[] result = "(char1)char2(char3)char4".split("\\(");I want :
result[0] = "(char1)char2" and
result[0] = "(char3)char4"
acutally char1,char2,char3, char4 ... is in the form of the below.
(any charactors except round brace)any charactors except round brace(any charactors except round brace)any charactors except round brace
I prefer String.split and Pattern.compile().split.
Edited by: iamjhkang on Feb 5, 2009 3:37 PM
Edited by: iamjhkang on Feb 5, 2009 3:41 PMiamjhkang wrote:
especially on
?= and ?<
Thanks.The following:
(?=...) // positive look ahead
(?!...) // negative look ahead
(?<=...) // positive look behind
(?<!...) // negative look behindare all "look-arounds". See: [http://www.regular-expressions.info/lookaround.html] -
Hi all,
I have a column(address) which I have to split into 4 parts. This may contain 1 or more lines(separated by new line). How to split this.
create table t(address varchar2(50));
insert into t values('first'||chr(10)||chr(13)||'second');
Antony Paul.Hi,
My first guess would be a simple substr with an instr.
Find the position of the chr(10) chr(13) combination and do a substring. It will not be very fast, but it will work.
An alternitive is using a function to return the values you need.
Jeroen
Maybe you are looking for
-
Error on ATP check when Creating a Sales Order
Hello, I encounter error on ATP check while creating a Sales Order. The error is when I create Sales Order using material A, with or with out indicating the Plant and Storage Location, the Purchase Order quantity is returned on ATP check, but when I
-
Thumbnail for standard wallpapers missing
Hi everyone, I have a problem with my Blackberry Q10. Today, while selecting a new wallpaper I noticed that a thumbnail image of a factory wallpaper (bb_blue) is missing. In the settings application as well as in the file manager the device only show
-
Read Implementation class attribute from context node
Hello all, I have a global atttribute in my Implementation class. How can I access this attribute from the getter setter method of an attribute in my Context node? Regards, Debolina
-
Error message when attempting to sync to itunes
Recently I have been having a problem syncing my iphone (original model 16 gb OS 2.2.1 with iTunes (8.0). I get a message that says unable to read from iphone. I can work around this by forcing the iphone to reboot. I can then perform a normal sync.
-
How can i extend the table control while transfering the data
hi how can i extend the table control while transfering the data.