How to use SQL query to make second line after character "|"? - sql

May I know how to use SQL select query to make new line after character ("|") ?

You can use REPLACE as follows:
replace(your_str,'|',chr(10))
db<>fiddle

If you mean new line in SQL you can try it
DECLARE #NewLineChar AS CHAR(2) = CHAR(13) + CHAR(10)
PRINT ('SELECT FirstLine AS MyFirstLine ' + #NewLineChar + 'SELECT SecondLine AS MySecondLine')

you can also this table-value function. you can set your entire text into function as well as a delimiter that is "|" in your case, finally it return multiple records based on how many "|" was exist.
ALTER FUNCTION [dbo].[Split] ( #string NVARCHAR(MAX), #delimiter CHAR(1)) RETURNS #output TABLE(splitdata NVARCHAR(MAX))
BEGIN
DECLARE #start INT, #end INT
SELECT #start = 1, #end = CHARINDEX(#delimiter, #string)
WHILE #start < LEN(#string) + 1 BEGIN
IF #end = 0
SET #end = LEN(#string) + 1
INSERT INTO #output (splitdata)
VALUES(SUBSTRING(#string, #start, #end - #start))
SET #start = #end + 1
SET #end = CHARINDEX(#delimiter, #string, #start)
END
RETURN
END
If your problem wont solve feel free to ask again.
RaminHbb

Related

How to filter a string in SQL?

How to filter a string in SQL 2008?
SELECT FileName=reverse(left(reverse('\\PRODSERVER\D$\EXPORT\Data20160401.txt'),
charindex('\',reverse('\\PRODSERVER\D$\EXPORT\Data20160401.txt'),
1) - 1))
Above query returns the file name which is Data20160401.txt.
I need to fetch only the server name which is PRODSERVER.
Create a function to split your string
CREATE FUNCTION [dbo].[fnSplitString]
(
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
DECLARE #start INT, #end INT
SELECT #start = 1, #end = CHARINDEX(#delimiter, #string)
WHILE #start < LEN(#string) + 1 BEGIN
IF #end = 0
SET #end = LEN(#string) + 1
INSERT INTO #output (splitdata)
VALUES(SUBSTRING(#string, #start, #end - #start))
SET #start = #end + 1
SET #end = CHARINDEX(#delimiter, #string, #start)
END
RETURN
END
Invoke the function
select *from dbo.fnSplitString('\\PRODSERVER\D$\EXPORT\Data20160401.txt','\')
Output
PRODSERVER
D$
EXPORT
Data20160401.txt
DECLARE #path VARCHAR(50) = '\\PRODSERVER\D$\EXPORT\Data20160401.txt'
Select SubString(#path,3,(CHARINDEX('\',#path,3)-3))
Asuming the path of your file always starts with \\ you could do something like:
Filename=substring(string,0,charindex(substring(string,2,len(string)-2),'\')
Don't know if this is the exact correct syntax as I am not on a machine with any sql processor at the moment but it should do something like this:
Get the substring of your string without the leading \\
Get the location of the 3rd \ as that is where the part you dont need starts
Grab the substring from the substring you created in 1 from first position after the \\ until the position of the 3rd \

how to get the char inbetween hyphen

qa-raj-ra
I want to get raj from the above string.
Length of the character in between hyphen may vary.
If you need only part of your string, you can use the inbuilt SPLIT function in MS SQL Server.
Given the delimiter, it will split the string for you.
This query below might help return the required result;
DECLARE #string NVARCHAR(MAX),
#delimiter CHAR(1),
#start INT,
#end INT
create TABLE #output (ID int IDENTITY(1,1) PRIMARY KEY, splitdata NVARCHAR(MAX))
SET #string = 'qa-raj-ra'
SET #delimiter = '-'
SELECT #start = 1, #end = CHARINDEX(#delimiter, #string)
WHILE #start < LEN(#string) + 1 BEGIN
IF #end = 0
SET #end = LEN(#string) + 1
INSERT INTO #output (splitdata)
VALUES(SUBSTRING(#string, #start, #end - #start))
SET #start = #end + 1
SET #end = CHARINDEX(#delimiter, #string, #start)
END
SELECT splitdata FROM #output
WHERE ID = 2
For a better use, you can put the query into a stored procedure and use #string as parameter.
The following is a quick and nasty way of getting your result via a query (on MySQL).
SELECT LEFT(RIGHT('qa-raj-ra',LENGTH('qa-raj-ra')-INSTR('qa-raj-ra','-')),
INSTR(RIGHT('qa-raj-ra',LENGTH('qa-raj-ra')-INSTR('qa-raj-ra','-')),'-')-1);
http://sqlfiddle.com/#!2/d41d8/48020
You can replace the hard coded string with whatever you want and it will return the text between the two hyphens.
In Postgres you can use string_to_array()
select (string_to_array('qa-raj-ra', '-'))[2]

UDF to insert a text string in to each row of a table

I've been searching high and low for an answer and I can't seem to find anything that points me in the right direction.
I need to create a UDF that will extract each word of a text string and return a table with each word of the string in a separate row.
The UDF is only able to take in one variable '#mytext'.
We can assume that the text string is separated by a single space and may contain commas or periods.
For example, "don’t worry about failures, worry about the chances you miss when you don’t even try." would need to return a table with each word on a separate row of a column without the commas or periods present.
I'm figuring that the text string would need to be separated with a common value that could be used to separate each word for insert, but I could totally be wrong.
Any help with this would be really appreciated!
Based on what I've said so far, here is my far from complete code that I'm not too sure how to proceed with
create function [dbo].[textConverter]
(
#mytext nvarchar(max)
)
returns #text_string table
(
word nvarchar
)
as
begin
set #mytext = replace(#mytext, 'what needs to be changed', 'what it needs to be changed too')
--insert string to table
end
EDIT
I've checked out a couple of links and uncovered a little more information on this, I've now got this code. However it exits with an error. The example that was used in the article I found the code on used numbers in the insert so maybe this is the issue??
create function [dbo].[textConverter]
(
#mytext varchar(max)
)
returns #text_string table
(
word nvarchar
)
as
begin
--Change string to be seperated by commas
set #mytext = replace(#mytext, ' ', ',')
set #mytext = replace(#mytext, '.',',')
--Eliminate double commas
set #mytext = replace(#mytext, ',,', ',')
declare #name nvarchar(255)
declare #pos int
while CHARINDEX(',', #mytext) > 0
begin
select #pos = CHARINDEX(',', #mytext)
select #name = SUBSTRING(#mytext, 1, #pos-1)
insert into #text_string
select #name
select #mytext = SUBSTRING(#mytext, #pos+1, LEN(#mytext)-#pos)
end
insert into #text_string
select #mytext
return
end
--To use function
select * from dbo.textConverter('don’t worry about failures, worry about the chances you miss when you don’t even try.')
See the answer below, It is not in complete shape, but can be developed into a user defined function.
Declare #Sentence Varchar(max) = 'don’t worry about failures, worry about the chances you miss when you don’t even try.'
Set #Sentence = Replace(Replace(Replace(Replace(#Sentence,',',' '),'.',' '),' ',' '),' ',' ')
Declare #e int = (Select Len(#Sentence) - Len(Replace(#Sentence,' ','')))
Declare #s int = 1
Declare #Result Table(id int identity(1,1),Words varchar(max))
--Select #s,#e
While #s <= #e
begin
Insert into #Result
Select Left(#Sentence,Charindex(' ',#Sentence,1)-1)
Set #Sentence = Substring(#Sentence,Charindex(' ',#Sentence,1) + 1,Len(#Sentence) )
Set #s = #s + 1
End
Insert into #Result
Select #Sentence
Select * from #Result
Result
----+-----------
id |Words
----+-----------
1 |don’t
2 |worry
3 |about
4 |failures
5 |worry
6 |about
7 |the
8 |chances
9 |you
10 |miss
11 |when
12 |you
13 |don’t
14 |even
15 |try
----+-----------
I adapted some of the code from http://sqlperformance.com/2012/07/t-sql-queries/split-strings as my situation meant that the delimiter couldn't specified as input. I could only use on input and that was the text string. As such, the following worked for me:
create function [dbo].[textConverter]
(
#string nvarchar(max)
)
returns #output table(splitdata nvarchar(max)
)
begin
--Change string to be seperated by commas
set #string = replace(#string, ' ', ',')
set #string = replace(#string, '.',',')
--Eliminate double commas
set #string = replace(#string, ',,', ',')
declare #start int, #end int
select #start = 1, #end = charindex(',',#string)
while #start < len(#string) + 1
begin
if #end = 0
set #end = len(#string) + 1
insert into #output (splitdata)
values(substring(#string, #start, #end - #start))
set #start = #end + 1
set #end = charindex(',', #string, #start)
end
return
end

Splitting an SQL string into multiple strings

I am trying to split a single string containing multiple email address data into three variables. The strings mark the start/end of an email address with the ; character.
An example string would be:
'joebloggs#gmailcom;jimbowen#aol.com;dannybaker#msn.com'
The code I currently have for this is as follows:
DECLARE #Email VARCHAR(100),
#Email2 VARCHAR(100),
#Email3 VARCHAR(100)
SET #Email = 'joebloggs#gmailcom;jimbowen#aol.com;dannybaker#msn.com'
SET #Email2 = SUBSTRING(#Email, CHARINDEX(';', #Email)+1, LEN(#Email))
SET #Email3 = SUBSTRING(#Email, CHARINDEX(';', #Email)+1, LEN(#Email))
SET #Email = SUBSTRING(#Email, 1, CHARINDEX(';', #Email)-1)
Unfortunately this doesn't seem to work. Could someone please point out where I am going wrong and what I should do to fix my problem?
Thanks in advance.
Assuming that there will always be 3 email addresses - the following seems to work;
DECLARE #Email VARCHAR(100),
#Email2 VARCHAR(100),
#Email3 VARCHAR(100)
SET #Email = 'joebloggs#gmailcom;jimbowen#aol.com;dannybaker#msn.com'
SELECT #Email = LEFT(#Email, CHARINDEX(';', #Email) - 1)
,#Email2 = SUBSTRING (
#Email,
CHARINDEX(';', #Email) + 1,
CHARINDEX(';', #Email, CHARINDEX(';', #Email) + 1) - LEN(LEFT(#Email, CHARINDEX(';', #Email) )) - 1
)
,#Email3 = RIGHT(#Email, CHARINDEX(';', #Email)-1)
This solution:
create function dbo.SplitString
(
#str nvarchar(max),
#separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
select
cast(1 as bigint),
cast(1 as bigint),
charindex(#separator, #str)
union all
select
p + 1,
b + 1,
charindex(#separator, #str, b + 1)
from tokens
where b > 0
)
select
p-1 ItemIndex,
substring(
#str,
a,
case when b > 0 then b-a ELSE LEN(#str) end)
AS Item
from tokens
);
GO
Taken from How do I split a string so I can access item x
In SQL Server 2016 you can use the built-in STRING_SPLIT function.
SELECT value FROM STRING_SPLIT(#var, ';')
Try using XML nodes to split and parse your string. Code sample below:
declare #Email as varchar(100), #del as varchar(10), #xml as xml;
set #Email='joebloggs#gmailcom;jimbowen#aol.com;dannybaker#msn.com';
set #del =';';
set #xml = '<root><c>' + replace(#Email,#del,'</c><c>') + '</c></root>';
select email.value('.','varchar(100)') as Email
from #xml.nodes('//root/c') as records(email);
Here this works I came across it quite sometime ago. Cannot take any credit for the work but this will work perfectly.
CREATE FUNCTION [dbo].[fnSplitString]
(
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
DECLARE #start INT, #end INT
SELECT #start = 1, #end = CHARINDEX(#delimiter, #string)
WHILE #start < LEN(#string) + 1 BEGIN
IF #end = 0
SET #end = LEN(#string) + 1
INSERT INTO #output (splitdata)
VALUES(SUBSTRING(#string, #start, #end - #start))
SET #start = #end + 1
SET #end = CHARINDEX(#delimiter, #string, #start)
END
RETURN
END
select *from dbo.fnSplitString('joebloggs#gmailcom;jimbowen#aol.com;dannybaker#msn.com',';')
I wrote this function that I use on a regular basis...
CREATE FUNCTION func_split(#value VARCHAR(8000), #delim CHAR)
RETURNS
#outtable TABLE (
i INTEGER,
value VARCHAR(1024)
)
AS
BEGIN
DECLARE #pos INTEGER
DECLARE #count INTEGER
IF LEN(#value) > 0
BEGIN
SET #count = 1
SET #value = #value + #delim
SET #pos = CHARINDEX(#delim, #value, 1)
WHILE #pos > 0
BEGIN
INSERT INTO #outtable (i, value) VALUES (#count, LEFT(#value, #pos - 1))
SET #value = RIGHT(#value, LEN(#value) - #pos)
SET #pos = CHARINDEX(#delim, #value, 1)
SET #count = #count + 1
END
END
RETURN
END
You when then call it with...
DECLARE #emails AS TABLE (
i INTEGER,
value VARCHAR(1024)
)
INSERT INTO #split SEELCT * FROM func_split('joebloggs#gmailcom;jimbowen#aol.com;dannybaker#msn.com', ';');
...and you end up with a temp table full of email addresses, i being their input order.
Your best bet is to turn the delimited string into columnar form and work from there.
You can use the iterative method, or the method using the Numbers table (which I prefer):
declare
#list varchar(1000),
#sep char(1)
set #list = 'joebloggs#gmailcom;jimbowen#aol.com;dannybaker#msn.com';
set #sep = ';'
-- iterative method
declare #res table (
c varchar(100)
)
declare
#pos_start int,
#pos_end int,
#len_sep int,
#exit int
select #pos_start = 1, #pos_end = 1, #len_sep = len(#sep), #exit = 0
while #exit = 0
begin
set #pos_end = charindex(#sep, #list, #pos_start)
if #pos_end <= 0 begin
set #pos_end = len(#list) + 1
set #exit = 1
end
insert #res(c) select substring(#list, #pos_start, #pos_end - #pos_start)
set #pos_start = #pos_end + #len_sep
end
select * from #res
-- the Numbers table method
select substring(#list, n, charindex(#sep, #list + #sep, n) - n)
from numbers
where substring(#sep + #list, n, 1) = #sep
and n < len(#list) + 1

SQL/Sybase database not returning results

I am passing a variable to the database that contains a list of companies... the var is passing but the database is not returning a result. How do I pass the list? and what kind of Where statement would I use?
If we are passing a comma seperated list to a stored procedure to retrieve a number of records that have one of these strings as a value in a field we use a SQL function. This function returns a table wich can be used to filter the data.
This is our function (you should execute the create before using it)
CREATE FUNCTION [dbo].[GetTableFromString]
(
#string NVARCHAR(4000),
#separator CHAR
)
RETURNS #resultTable TABLE (string NVARCHAR(255))
AS
BEGIN
DECLARE #myString NVARCHAR(255)
IF (LEN(#string) > 0)
BEGIN
DECLARE #start INT,
#charIndex INT
SET #start = 1
SET #charIndex = CHARINDEX(#separator, #string, #start) -- Get the position of the first seperator
WHILE ( #charIndex >= 0 )
BEGIN
IF #charIndex = 0 -- No seperator found, take the whole string and insert it in the result table
BEGIN
SELECT #myString = SUBSTRING(#string, #start, LEN(#string) - #start + 1)
SET #charIndex = -1
END
ELSE
BEGIN
SELECT #myString = SUBSTRING(#string, #start, CHARINDEX(#separator, #string, #start) - #start)
SET #start = CHARINDEX(#separator, #string, #start) + 1 -- Set the start position of the char after the seperator
SET #charIndex = CHARINDEX(#separator, #string, #start) -- Get the position of the next seperator
END
INSERT INTO #ResultTable (string) VALUES (#myString)
END
END
RETURN
END
This is how the function then can be used:
SELECT YourField1,
YourField2,
...
FROM YourTableName
WHERE YourFieldx In ( SELECT string
FROM dbo.GetTableFromString('IBM,WalMart,KMart', ','))
I think you need to post what you're doing.
It sounds almost as if you had a VARCHAR variable containing a comma separated list to a stored procedure, in which case the SP would need to use dynamic sql, but I can't tell.