How to get values enclosed within special characters in a long string - sql-server

I have a long string containing three special symbols ' # and ? and some text are enclosed inside these symbols.
for ex. "#sa#32#ddd#?222?#ds#asa#hhh#?ddsds?dsdsd?cccc?'cxcx'?ccxc?cxc?'cxcx'"
I want the values sa 32 ddd 222 ds etc.. and insert these values in a table.
Next step is to insert these values inside different column of same row in a table.
How can I achieve that.

The following function allows you to split the given string on the basis of a single delimiter.
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
You can use this function iteratively for each of the individual delimiters, over each individual string obtained from the first run and the final output should provide you the requisite values.

Try this way. The complete answer It depends od more information
SET QUOTED_IDENTIFIER OFF
declare #test varchar(100)
set #test ="#sa#32#ddd#?222?#ds#asa#hhh#?ddsds?dsdsd?cccc?'cxcx'?ccxc?cxc?'cxcx'"
print replace(replace(#test,'#',' '),'?',' ')

Related

Split in sql server

enter image description hereI have table having Column "Title" having multiple String value with comma I want to split it with comma & move to next line in same column is that possible with SQL SERVER.i want it in same row but next line.
Eg: Test1,Test2,Test3,Test4
Expected:
Test1
Test2
Test3
...
As you described it, you want the result to be in one field. So you do not want to split the value, but replace the , with a line break.
Select replace(title,',',char(13)+char(10))
SSMS does not show line breaks, but they are present in the result.
This code may helps you
IF OBJECT_ID('tempdb..#t') IS NOT NULL
DROP TABLE #t
CReate table #t (Title nvarchar(1000))
INSERT INTO #t
SELECT 'Test1,Test2,Test3,Test4'
SELECT
SPlit.a.value('.','nvarchar(1000)') AS Title FROM
(
SELECT
CAST('<S>'+REPLACE(Title,',','</S><S>')+'</S>' AS XML ) AS Title FROM #t
)A
CROSS APPLY Title.nodes('S') AS SPlit(a)
Result
Title
-----
Test1
Test2
Test3
Test4
Yes it is possible. You can create a function first to achieve it. Here is the function you can use :
CREATE FUNCTION [dbo].[fnSplitString]
(
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
DECLARE #start INT, #end INT, #temp varchar(max)
set #temp = ''
SELECT #start = 1, #end = CHARINDEX(#delimiter, #string)
WHILE #start < LEN(#string) + 1 BEGIN
IF #end = 0
SET #end = LEN(#string) + 1
SET #temp = #temp + CHAR(13)+CHAR(10) + SUBSTRING(#string, #start, #end - #start)
SET #start = #end + 1
SET #end = CHARINDEX(#delimiter, #string, #start)
END
INSERT INTO #output (splitdata)
VALUES(#temp)
RETURN
END
And then you can make the query like below :
select *from dbo.fnSplitString('Test1,Test2,Test3,Test4',',')

Convert comma delimited string to table or array in sql server 2008 without using dbo.split

How to convert comma delimited string to table or array in sql server 2008 without using dbo.split function because the system doesn’t support this function?
Eg of string: ’12,14,15’
Change this to
*Table column*
12
14
15
Or array=[12,14,15]
I would like to insert comma separated string values into a table ultimately.
Thanks
dbo.split is probably user defined function, so you need to define it. Otherwise you can use XML + CROSS APPLY:
Demo
DECLARE #string NVARCHAR(100) = '12,14,15'
;WITH cte AS
(
SELECT
CAST('<XMLRoot><RowData>' + REPLACE(t.val,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
FROM (SELECT #string) AS t(val)
)
SELECT
m.n.value('.[1]','varchar(8000)')
FROM cte
CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)
If you don't want to use split, you can create your own custom function to achieve this.
Please follow below stack question for same.
How to convert comma separated NVARCHAR to table records in SQL Server 2005?
Below link covers all possible way to achieve this.
http://blogs.msdn.com/b/amitjet/archive/2009/12/11/sql-server-comma-separated-string-to-table.aspx
ALTER 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

Need to insert breaks in strings of very column with ' ' or ','

I have a table that has one Column but over 100,000 rows
Col_Name
qwchijhuirhxnihdiuyfnx
dhjhfiurhncnmxmzjcoinrds
xnbxknsiiuncirnxknrxnxz
I need to insert a '.' or '$' or some marker after every 3rd character
Example of result needed:
Col_Name
qwc.hij.hui.rhx.nih.diu.yfn.x
dhj.hfi.urh.ncn.mxm.zjc.oin.rds.
xnb.xkn.sii.unc.irn.xkn.rxn.xz
I originally solved this with:
INSERT INTO New_Table
(
c1
,c2
,c3
)
SELECT
substring(CAST(Col_Name AS VARCHAR(MAX)),1,3) as C1
,substring(CAST(Col_Name AS VARCHAR(MAX)),4,3) as C2
,substring(CAST(Col_Name AS VARCHAR(MAX)),7,3) as C3
From Table_Name
This causes problems later in the script so the data must remain in one column but could be inserted into a new table as long as it was a new table with just one column
Here's a sqlfiddle starting point you can refactor http://sqlfiddle.com/#!6/ab6dd/1/0 using function and while loop.
You may be able to do something more efficient with regular expressions or SQLCLR if you need speed.
CREATE FUNCTION dotify (#input varchar(MAX))
RETURNS varchar(MAX)
AS
BEGIN
DECLARE #output varchar(MAX) = ''
declare #index int = 0
declare #length int
set #length = len(#input)
while #index <= #length
begin
SET #output = #output + substring(#input, #index, 1)
if (#index % 3) = 0 AND #index > 0
BEGIN
SET #output = #output +'.'
END
set #index = #index + 1
end
return(#output)
END
GO
select TOP 10000 col_name, dbo.dotify(col_name) FROM old_table
You can use TOP to limit the processing time to a few seconds so you can easily profile efficiency changes you make.

Select IN using varchar string with comma delimited values

I am trying to search several tables for a list of phones.
The problem is converting the single string into a valid comma delimited string to use in conjunction with the IN clause.
I tried using replace to fix the problem.
DECLARE #PhoneNumber VARCHAR(3000)
SET #PhoneNumber = '6725556666,2124444444'
SET #PhoneNumber = '''' + #PhoneNumber + ''''
SELECT #PhoneNumber
'6725556666','2124444444'
Finally the sample SQL does not recognize the string as expected:
SELECT Provider
,PhoneNumber
,ChangeType
,ChangeDate
FROM dbo.PhoneLog
WHERE PhoneNumber IN (#PhoneNumber)
There are several ways to handle this. One option is to use dynamic sql and inject your phone number string into a variable containing the statement and then executing that like this:
DECLARE #PhoneNumber VARCHAR(3000)
SET #PhoneNumber = '6725556666,2124444444'
DECLARE #SQL NVARCHAR(max)
SET #SQL = N'
SELECT Provider, PhoneNumber, ChangeType, ChangeDate
FROM dbo.PhoneLog
WHERE PhoneNumber IN (' + #PhoneNumber + ')'
EXEC sp_executesql #SQL
Please note that this approach can be vulnerable to SQL injection attacks, for instance feeding a string like
SET #PhoneNumber = '1);truncate table phonelog;--'
would effectively empty the table. So using a dynamic SQL approach like above should only be an option if it's certain that the string fed that in injected is sanitized and safe (or maybe it should never be used).
Another, possibly better, option is to use a user defined function to split the phonenumber variable and use that like this:
SELECT Provider, PhoneNumber, ChangeType, ChangeDate
FROM dbo.PhoneLog
WHERE PhoneNumber IN (
SELECT splitdata FROM dbo.fnSplitString(#PhoneNumber,',')
-- you could add a check here that the data returned from the function
-- is indeed numeric and valid
-- WHERE ISNUMERIC(splitdata) = 1
)
Here's the function used in the example:
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
I did not write the function, I think I got it somewhere on the internet...

How do i split strings in SQL server? [duplicate]

This question already has answers here:
How do I split a delimited string so I can access individual items?
(46 answers)
Closed 8 years ago.
Let's say i have a string.
"Hello this is a "string need" to split"
I need to get he output as
Hello
this
is
a
string need
to
split
Any help would be appreciated.
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
This will Split the string into Words, from there you have to be more specific on what substring you want from the initial string.
This is for SQL Server.

Resources