How to insert data from String in table? - sql

I have on table PersonDetail which contains NAME and AGE as column.
I am using one application which is taking all data as String by comma and pipe separated value like 'Acton,58|Nairi,20|Sara,14|Denny,52' (Format is same as given)
I want to insert that data into table(PersonDetail) but I don't know how can I separate it as a NAME and AGE.
Some one suggested me to create function which can separate the data, But i have no idea to do it.
Can any one give me suggestion??
Thanks in advance :)

you can create Multi-statement table value function to separate the data.
you just need to insert each NAME and AGE into table type variable and after inserting you should return that table as given below.
CREATE FUNCTION UDF_InsertDataFromString
(
#dataString VARCHAR(5000)
)
RETURNS #insertedData TABLE
(
NAME VARCHAR(30),
AGE INT
)
AS
BEGIN
DECLARE #pipeIndex INT,
#commaIndex INT,
#LENGTH INT,
#NAME VARCHAR(100),
#AGE INT
SELECT #LENGTH = LEN(RTRIM(LTRIM(#dataString))),
#dataString = RTRIM(LTRIM(#dataString))
WHILE (#LENGTH <> 0)
BEGIN
SELECT #LENGTH = LEN(#dataString),
#commaIndex = CHARINDEX(',', #dataString),
#pipeIndex = CHARINDEX('|', #dataString)
IF(#pipeIndex = 0) SET #pipeIndex = #LENGTH +1
SELECT #NAME = RTRIM(LTRIM(SUBSTRING(#dataString, 1, #commaIndex-1))),
#AGE = RTRIM(LTRIM(SUBSTRING(#dataString, #commaIndex+1, #pipeIndex-#commaIndex-1))),
#dataString = RTRIM(LTRIM(SUBSTRING(#dataString, #pipeIndex+1, #LENGTH-#commaIndex-1)))
INSERT INTO #insertedData(NAME, AGE)
VALUES(#NAME, #AGE)
SELECT #LENGTH = LEN(#dataString)
END
RETURN
END
Now you can use this function while inserting data from string, you just need to pass string as parameter in function as given below.
DECLARE #personDetail TABLE(NAME VARCHAR(30), AGE INT)
INSERT INTO #personDetail(NAME, AGE)
SELECT NAME, AGE
FROM dbo.UDF_InsertDataFromString('Acton,58|Nairi,20|Sara,14|Denny,52')
SELECT NAME, AGE
FROM #personDetail

use this split func
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
and then use this query
DECLARE #x table ( id int identity(1,1)
, str varchar(50) )
DECLARE #str varchar(50)='Acton,58|Nairi,20|Sara,14|Denny,52'
INSERT INTO #x
SELECT *
FROM [dbo].[fnSplitString] (#str ,'|')
SELECT *
from #x
DECLARE #y int=(SELECT count(*)
FROM #x)
DECLARE #e varchar(50)
DECLARE #b varchar(50)
DECLARE #c varchar(50)
WHILE #y!=0
BEGIN
set #e =(SELECT str
FROM #x
where id=#y)
set #b =(substring(#e,1,(charindex(',',#e)-1)))
set #c = (substring(#e,(charindex(',',#e)+1),len(#e)-charindex(',',#e)))
INSERT INTO PersonDetail
SELECT distinct #b
, #c
FROM #x
SET #y=#y-1
END

yes you can create your own function.
just you need to apply different string function for that
https://msdn.microsoft.com/en-IN/library/ms181984.aspx

Related

SQL Query for searching for a specific part of a string in a column

I want to search for a specific part of a nvarchar text string in a column.
The text string is structured like this X#2016-06-17#7483631#2016-06-27#2#167890##920, it's split up by #. I want to find 6th text block, 167890 in this case.
Is there a simple way to do this?
Perhaps with a little XML
Example
Declare #YourTable table (SomeCol varchar(500))
Insert Into #YourTable values
('X#2016-06-17#7483631#2016-06-27#2#167890##920')
Select SomeCol
,Pos6 = cast('<x>' + replace(A.SomeCol,'#','</x><x>')+'</x>' as xml).value('/x[6]','varchar(50)')
From #YourTable A
Returns
SomeCol Pos6
X#2016-06-17#7483631#2016-06-27#2#167890##920 167890
Create a SPLIT function, returning each part with an index like below:
CREATE FUNCTION [dbo].[StringSplit_WithIndex] (#str_in VARCHAR(8000),#separator VARCHAR(4) ) RETURNS #strtable TABLE (strval VARCHAR(8000),rn INT IDENTITY(1,1)) AS
BEGIN
DECLARE
#Occurrences INT,
#Counter INT,
#tmpStr VARCHAR(8000)
SET #Counter = 0
IF SUBSTRING(#str_in,LEN(#str_in),1) <> #separator
SET #str_in = #str_in + #separator
SET #Occurrences = (DATALENGTH(REPLACE(#str_in,#separator,#separator+'#')) - DATALENGTH(#str_in))/ DATALENGTH(#separator)
SET #tmpStr = #str_in
WHILE #Counter <= #Occurrences
BEGIN
SET #Counter = #Counter + 1
INSERT INTO #strtable
VALUES ( SUBSTRING(#tmpStr,1,CHARINDEX(#separator,#tmpStr)-1))
SET #tmpStr = SUBSTRING(#tmpStr,CHARINDEX(#separator,#tmpStr)+1,8000)
IF DATALENGTH(#tmpStr) = 0
BREAK
END
RETURN
END
Then, all you need to use the "rn" field after splitting like:
DECLARE #s VARCHAR(255) = 'X#2016-06-17#7483631#2016-06-27#2#167890##920'
SELECT *
FROM [StringSplit_WithIndex](#s,'#')
WHERE rn=6

Insert into Table Variable values from a comma separated list

declare #List varchar(25) = '2,3,4'
declare #Delinquencies table (id int);
insert into #Delinquencies(id) values('2'),('3'),('4'); --Line in question
#List is being populated with a string populated from an SSRS report for which choices they have picked. Now the way my stored procedure is running, I need to be able insert into my table variable based on what varchar list is coming through. How can I insert into a table variable with a dynamic varchar list? What is listed here is about as close to the testing format as I can come.
I am using SQL Server 2008.
Example
#List = '1'
insert into #Delinquencies(id) values('1')
And any combination up to
#List = '1,2,3,4'
insert into #Delinquencies(id) values('1'),('2'),('3'),('4')
Using one of the split string functions from here..
declare #List varchar(25) = '2,3,4';
declare #Delinquencies table (id int);
;with cte
as
(select * from
[dbo].[SplitStrings_Numbers](#list,',')
)
insert into #Delinquencies(id)
select * from cte
u need to create a dbo.StringSplit function
which takes two parameter (string, delimiter)
CREATE function [dbo].[StringSplit](
#String varchar (max),
#Delimiter nvarchar (10)
)
returns #ValueTable table ([Value] varchar(max))
begin
declare #NextString varchar(max)
declare #Pos int
declare #NextPos int
declare #CommaCheck nvarchar(1)
--Initialize
set #NextString = ''
set #CommaCheck = right(#String,1)
--Check for trailing Comma, if not exists, INSERT
--if (#CommaCheck <> #Delimiter )
set #String = #String + #Delimiter
--Get position of first Comma
set #Pos = charindex(#Delimiter,#String)
set #NextPos = 1
--Loop while there is still a comma in the String of levels
while (#pos <> 0)
begin
set #NextString = substring(#String,1,#Pos - 1)
insert into #ValueTable ( [Value]) Values (#NextString)
set #String = substring(#String,#pos +1,len(#String))
set #NextPos = #Pos
set #pos = charindex(#Delimiter,#String)
end
return
end
and then you can use it like below
declare #List varchar(25) = '2,3,4'
SELECT value from dbo.StringSplit(#List,',')
Here is a parser which returns the sequence as well.
For example:
Select * from [dbo].[udf-Str-Parse]('126,256,512',',')
Returns
Key_PS Key_Value
1 126
2 256
3 512
The UDF
CREATE FUNCTION [dbo].[udf-Str-Parse] (#String varchar(max),#Delimeter varchar(10))
--Usage: Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
-- Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
Returns #ReturnTable Table (Key_PS int IDENTITY(1,1), Key_Value varchar(max))
As
Begin
Declare #XML xml;Set #XML = Cast('<x>' + Replace(#String,#Delimeter,'</x><x>')+'</x>' as XML)
Insert Into #ReturnTable Select Key_Value = ltrim(rtrim(String.value('.', 'varchar(max)'))) FROM #XML.nodes('x') as T(String)
Return
End

Getting syntax error while using table variable in table value function in SQL Server 2012

I am trying to use table variable with table value function but I am getting a syntax error. Please help me to solve this.
Here is the code:
Create FUNCTION [dbo].[SplitStrings1]
(#List NVARCHAR(MAX),
#Delimiter NVARCHAR(255))
RETURNS #Results TABLE(Col1 int)
AS
BEGIN
declare #tblHelping table (Col1 int);
declare #i int
declare #rows_to_insert int
set #i = 1
set #rows_to_insert = 1000
while #i < #rows_to_insert
begin
INSERT INTO #tblHelping VALUES (#i)
set #i = #i + 1
end
(SELECT
Number = ROW_NUMBER() OVER (ORDER BY Number),
Item FROM (SELECT Number, Item = LTRIM(RTRIM(SUBSTRING(#List, Number,
CHARINDEX(#Delimiter, #List + #Delimiter, Number) - Number)))
FROM
(SELECT * FROM #tblHelping) AS n(Number)
WHERE
Number <= CONVERT(INT, LEN(#List))
AND SUBSTRING(#Delimiter + #List, Number, 1) = #Delimiter) AS y)
END
I am getting this error
A RETURN statement with a return value cannot be used in this context.
If you want to use your function then working version below. But there is better solution, please see:
Split strings the right way – or the next best way as recomended by
#SeanLange
How to split string using delimiter char using T-SQL?
How do I split a string so I can access item x?
.
CREATE FUNCTION [dbo].[SplitStrings1]
( #List NVARCHAR(MAX)
, #Delimiter NVARCHAR(255))
RETURNS #Results TABLE
(Number INT, Item NVARCHAR(MAX) )
AS
BEGIN
declare #tblHelping table (Col1 int);
declare #i int
declare #rows_to_insert int
SET #i = 1
SET #rows_to_insert = 1000
while #i < #rows_to_insert
begin
INSERT INTO #tblHelping VALUES (#i)
set #i = #i + 1
end
insert into #Results
SELECT Number = ROW_NUMBER() OVER (ORDER BY Number)
, Item
FROM (SELECT Number
, Item = LTRIM(RTRIM(SUBSTRING(#List, Number,CHARINDEX(#Delimiter, #List + #Delimiter, Number) - Number)))
FROM (SELECT * FROM #tblHelping) AS n(Number)
WHERE Number <= CONVERT(INT, LEN(#List))
AND SUBSTRING(#Delimiter + #List, Number, 1) = #Delimiter) AS y
RETURN
END
Or try something like that:
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

how extract sub-string from string in sybase?

With a query i get this string "Order::Resource(PPP32#BB300320LQ00J#AAAR05504)".
I want to extract string before, between and after # character as following:
id = PPP32
sub_id = BB300320LQ00J
sup_id =AAAR05504
Does anyone know how to do this?
Here's the correct solution:
declare #string varchar(50)
select #string = 'Order::Resource(PPP32#BB300320LQ00J#AAAR05504)'
declare #start int, #end int, #secondstring varchar(100)
select #start = charindex('#',#string)
select #secondstring = substring(#string, #start+1, len(#string))
select #end = charindex('#',#secondstring)
select substring(#string,charindex('(', #string)+1, #start-1-charindex('(', #string)),
substring(#string,#start+1,#end-1),
substring(#string, #start+#end+1, len(#string)-(#start+#end+1))
declare #start int, #end int, #secondstring varchar(100)
select #start = charindex('#',#string)
select #secondstring = substring(#string, #start+1, len(#string))
select #end = charindex('#',#secondstring)
select substring(#string,1, #start-1),
substring(#string,#start+1,#end-1),
substring(#string, #start+#end+1, len(#string)-#end)

T-SQL script or function that will get selected values from a comma delimited string

If I have a string with values like A,B,C,D,E,F, and I wanted to remove the last comma, is there a function or script I can use to do that?
The below example will trim off the last char of a string but wont care if it's a comma or not
DECLARE #s VARCHAR(50)
SET #s = 'a,b,'
SELECT LEFT(#s, LEN(#s)-1)
If I'm understanding you additional question correctly, I believe you want to archive something like the below...
DECLARE #b TABLE
(
[stuff] VARCHAR(2)
)
INSERT INTO #b VALUES('c')
DECLARE #s VARCHAR(MAX)
SET #s = 'a,b,c'
SELECT [stuff]
FROM #b b
INNER JOIN dbo.list(#s) lst
ON lst.val = b.[stuff]
CREATE function [dbo].[list] ( #list VARCHAR(MAX) )
RETURNS #list_table TABLE ([val] VARCHAR(20))
AS
BEGIN
DECLARE #index INT,
#start_index INT,
#val VARCHAR(20)
SELECT #index = 1
SELECT #start_index = 1
WHILE #index <= DATALENGTH(#list)
BEGIN
IF SUBSTRING(#list,#index,1) = ','
BEGIN
SELECT #val = SUBSTRING(#list, #start_index, #index - #start_index )
INSERT #list_table ([val]) VALUES (#val)
SELECT #start_index = #index + 1
END
SELECT #index = #index + 1
END
SELECT #val = SUBSTRING(#list, #start_index, #index - #start_index )
INSERT #list_table ([val]) VALUES (#val)
RETURN
END
The function just splits up the input string into rows in a table with a column "val" - this means you can then pass in a comma delimited string and use it to filter another table.