ReCursive/While Loop - sql

I am trying to build a view that looks at a table that has three columns; Building, Lane, Lot. I need to be able to loop through the table dynamically to display the Building, Lane and Lot all on one row.
Sample:
>Building Lane Lot
> 1 1001 56789
> 1 1002 12489
> 1 1002 37159
> 1 1002 71648
> 3 3001 27489
> 3 3001 67154
> 3 3002 47135
> 3 3003 84271
> 3 3003 96472
> 3 3003 94276
Results
> Building Lane Lots
> 1 1001 56789
> 1 1002 12489, 37159, 71648
> 3 3001 27489, 67154
> 3 3002 47135
> 3 3003 84271, 96472, 94276
I tried a recursion union but received a message that I had exceded the max amount of 100.
I also tried a loop but it just kept going and did not concantenate as I had hoped.
So far in the table there are over 300 lot numbers for one building in one lane with the potential of huders more.

It looks like you're looking for something similar to the below script (see this SQL Fiddle example):
DECLARE #row TABLE (
A VARCHAR(1),
AA VARCHAR(1),
B VARCHAR(4)
)
INSERT INTO #row VALUES(1,1,1001)
INSERT INTO #row VALUES(1,1,1002)
INSERT INTO #row VALUES(1,1,1003)
INSERT INTO #row VALUES(1,2,1001)
INSERT INTO #row VALUES(2,1,1001)
INSERT INTO #row VALUES(2,1,1002)
INSERT INTO #row VALUES(2,1,1003)
INSERT INTO #row VALUES(2,1,1004)
INSERT INTO #row VALUES(2,1,1005)
INSERT INTO #row VALUES(2,2,1001)
INSERT INTO #row VALUES(2,2,1002)
INSERT INTO #row VALUES(3,1,1001)
SELECT *
FROM #row
SELECT r1.A
, r1.AA
, STUFF((SELECT ', ' + r2.B AS [text()]
FROM #row r2
WHERE r1.A = r2.A AND r1.AA = r2.AA
ORDER BY r2.B
FOR XML PATH('')),1,1,'') AS "Row"
FROM #row r1
GROUP BY A, AA
So for your query, it will look something like this:
SELECT r1.Building
, r1.Lane
, STUFF((SELECT ', ' + r2.Lot AS [text()]
FROM YourTable r2
WHERE r1.Building = r2.Building AND r1.Lane = r2.Lane
ORDER BY r2.Lot
FOR XML PATH('')),1,1,'') AS "Row"
FROM YourTable r1
GROUP BY Building, Lane

Related

Use PATINDEX to extract a substring in SQL Server?

I have some specific values I want to extract out of a string in SQL Server, but I'm not sure exactly how to get it done with PATINDEX.
Take this string:
declare #Command nvarchar(500) = 'IF dbo.SomeFunctionFn() = 1 BEGIN EXEC SomeStoredProcPR #RowsPerRun=500000, #RowsPerBatch=10000, #NbrDaysToKeepRpt=7 END'
I want to extract out the values of 500000 (for #RowsPerRun), 10000 for #RowsPerBatch and the value of 7 for #NbrDaysToKeepRpt. The values will be of variable length, so I can't guarantee the #RowsPerRun value will be 6 characters.
Is that possible?
DECLARE #Command NVARCHAR(500) =
'IF dbo.SomeFunctionFn() = 1 BEGIN EXEC SomeStoredProcPR #RowsPerRun=500000, #RowsPerBatch=10000, #NbrDaysToKeepRpt=7 END'
SELECT
SearchItem = srch.Txt,
ItemIndex = st.Pos,
ItemLen = t.Ln,
Item = SUBSTRING(pfx.Txt,1,t.Ln)
FROM (VALUES('#RowsPerRun='),('#RowsPerBatch='),('#NbrDaysToKeepRpt=')) AS srch(Txt)
CROSS APPLY (VALUES(CHARINDEX(srch.Txt,#Command),LEN(srch.Txt))) AS st(Pos,Ln)
CROSS APPLY (VALUES(SUBSTRING(#Command, st.Pos+st.Ln, 500))) AS pfx(Txt)
CROSS APPLY (VALUES(PATINDEX('%[^0-9]%',pfx.Txt)-1)) AS t(Ln);
Returns:
SearchItem ItemIndex ItemLen Item
------------------ ----------- ----------- --------
#RowsPerRun= 59 6 500000
#RowsPerBatch= 79 5 10000
#NbrDaysToKeepRpt= 100 1 7
Note that I included a few extra columns to help you understand what's happening.
Update: Against a table
This is how you would apply this logic to a series of values:
DECLARE #sometable TABLE (CommandId INT IDENTITY, Command NVARCHAR(500));
INSERT #sometable (Command)
VALUES
('IF dbo.SomeFunctionFn() = 1 BEGIN EXEC SomeStoredProcPR #RowsPerRun=500000, #RowsPerBatch=10000, #NbrDaysToKeepRpt=7 END'),
('IF dbo.SomeFunctionFn() = 5 BEGIN EXEC SomeStoredProcPR #RowsPerRun=123, #RowsPerBatch=500, #NbrDaysToKeepRpt=20 END'),
('IF dbo.SomeFunctionFn() = 5 BEGIN EXEC XXX #RowsPerRun=43, #RowsPerBatch=1000, #NbrDaysToKeepRpt=120 END'),
('IF dbo.SomeFunctionFn() = 5 BEGIN EXEC abc.yyy #RowsPerRun=43, #RowsPerBatch=1000, #NbrDaysToKeepRpt=120 END');
SELECT t.CommandId, f.SearchItem, f.Item
FROM #sometable AS t
CROSS APPLY
(
SELECT
SearchItem = srch.Txt,
ItemIndex = st.Pos,
ItemLen = t.Ln,
Item = SUBSTRING(pfx.Txt,1,t.Ln)
FROM (VALUES('#RowsPerRun='),('#RowsPerBatch='),('#NbrDaysToKeepRpt=')) AS srch(Txt)
CROSS APPLY (VALUES(CHARINDEX(srch.Txt,t.Command),LEN(srch.Txt))) AS st(Pos,Ln)
CROSS APPLY (VALUES(SUBSTRING(t.Command, st.Pos+st.Ln, 500))) AS pfx(Txt)
CROSS APPLY (VALUES(PATINDEX('%[^0-9]%',pfx.Txt)-1)) AS t(Ln)
) AS f;
Returns:
CommandId SearchItem Item
----------- ------------------ --------
1 #RowsPerRun= 500000
1 #RowsPerBatch= 10000
1 #NbrDaysToKeepRpt= 7
2 #RowsPerRun= 123
2 #RowsPerBatch= 500
2 #NbrDaysToKeepRpt= 20
3 #RowsPerRun= 43
3 #RowsPerBatch= 1000
3 #NbrDaysToKeepRpt= 120
4 #RowsPerRun= 43
4 #RowsPerBatch= 1000
4 #NbrDaysToKeepRpt= 120

How to get parents up to 5 level hierarchy from child id

I created a table with name "content_folder" and inserted values just like this.
cf_id cf_parent_id cf_name
--------------------------------------
1 0 root
2 1 US Blenders
3 2 US Blenders Chil11
4 1 Australian Blenderss
5 1 US Blenders Chil11 -2
40003 1 Child
40206 1 Child 111
40211 2 New
I want to display the folder hierarchy for 5 levels sepereated by '>' in drop drown so I wanted the result in following way
cf_id path
--------------------------------------
1 root
2 US Blenders
3 US Blenders > US Blenders Chil11
4 Australian Blenderss
5 US Blenders Chil11 -2
40003 Child
40206 Child 111
40211 US Blenders > New
I tried by writing following query but output result is not proper.
SELECT t.cf_id,
Group_concat(anc.cf_name ORDER BY anc.cf_name SEPARATOR ' > ') AS path
FROM content_folder AS t
JOIN content_folder AS anc
ON t.cf_name LIKE Concat(anc.cf_name, '%')
GROUP BY t.cf_id;
Can you please suggest me better solution. I am working on MySQL 5.7 so I think CTEs are not supported in this version.
I had done something like this with my database. Here is how i did it, i changed a few things and added the two update statements at the end to get your desired output, but i think you will get the gist of whats going on:
DECLARE #temp TABLE
(
id INT,
parent_id INT,
name NVARCHAR(100),
path NVARCHAR(MAX)
)
INSERT INTO #temp (id,parent_id,name) VALUES
(1,0,'root'),
(2,1,'US Blenders'),
(3,2,'US Blenders Chil11'),
(4,1,'Australian Blenderss'),
(5,1,'US Blenders Chil11 -2'),
(40003,1,'Child'),
(40206,1,'Child 111'),
(40211,2,'New')
DECLARE #counter TABLE ( id INT )
DECLARE #current_id INT;
DECLARE #loc_id INT;
INSERT INTO #counter SELECT id FROM #temp
SELECT * FROM #temp
WHILE (SELECT COUNT(*) FROM #counter) > 0
BEGIN
SET #current_id = (SELECT TOP 1 id FROM #counter)
SET #loc_id = (SELECT parent_id FROM #temp WHERE id = #current_id)
WHILE #loc_id IS NOT NULL AND #loc_id != 0
BEGIN
UPDATE #temp
SET path = ' > ' + (SELECT name FROM #temp WHERE id = #loc_id) + CASE WHEN path IS NULL THEN '' ELSE path END
WHERE id = #current_id
SET #loc_id = (SELECT parent_id FROM #temp WHERE id = #loc_id)
END
DELETE FROM #counter
WHERE id = #current_id
END
UPDATE #temp
SET path = REPLACE(REPLACE(path,' > root',''),' > ','')
UPDATE #temp
SET path = CASE WHEN LEN(path) > 0 THEN path + ' > ' + name ELSE name END
SELECT * FROM #temp
OUTPUT:
id parent_id name path
1 0 root root
2 1 US Blenders US Blenders
3 2 US Blenders Chil11 US Blenders > US Blenders Chil11
4 1 Australian Blenderss Australian Blenderss
5 1 US Blenders Chil11 -2 US Blenders Chil11 -2
40003 1 Child Child
40206 1 Child 111 Child 111
40211 2 New US Blenders > New

T-SQL - How can I split a variable into 4 columns for output?

This is a T-SQL question, I use Microsoft SQL Server 2014. I am joining three tables, which is very straightforward. The tricky part is this: one of the variables, SubtotalKey, takes the form ‘ABD_1999_MAE_1’. I would like to split this variable into its four components, delimited by the underscore, and include the four columns in my output at a specific point in the query. I have a workable solution which uses a scalar function. Workable in the sense that it does what I have just described…but there are performance issues which render it unusable. I’ve since converted the scalar function to a table-valued function, and am using ‘outer apply’ on it as a solution. Unfortunately, this results in 4 rows in the output per result row from the join. Not sure where to go from here - I tried pivot but pivot needs numerical columns to pivot, I think. All help much appreciated.
The table value function in the code below, ufn_SplitString, will split the string above into a table with 1 column and 4 rows. The 4 rows contain the values, respectively, ABD, 1999, MAE, 1.
For the purposes of this question, there are 4 elements in SubtotalKey, but in reality, the number will be variable. Is a solution possible, if I don’t know in advance what the number of required extra columns will be?
Here is my code so far:
SELECT
t1.t_proj AS time_period,
ufn.item,
t3.AnnClaimVal AS annuity_outgo_smbel,
t3.DeathClaimVal AS death_outgo_smbel,
t2.SolvSurvXCF AS annuity_outgo_reins,
t2.SolvDeathXCF AS death_outgo_reins,
t2.ReinSwapXCF AS mortswap_fixedleg_payment,
t3.ExpenseValXCF AS ren_exp,
t1.InvExpSCF AS inv_exp,
t1.InvExpReinSCF AS inv_exp_reins
FROM [sch_ImmAnn].[viw_mdlEV_Formulae] t1
INNER JOIN [sch_ImmAnn].[viw_mdl_Formulae] t2
ON t1.t_proj = t2.t_proj AND t1._SubtotalKey = t2._SubtotalKey AND t1._Scenario = t2._Scenario AND t1._ExecRun_UID = t2._ExecRun_UID
INNER JOIN [sch_ImmAnn].[viw_mdlValue_Formulae] t3
ON t1.t_proj = t3.t_proj AND t1._SubtotalKey = t3._SubtotalKey AND t1._Scenario = t3._Scenario AND t1._ExecRun_UID = t3._ExecRun_UID
OUTER APPLY sch_Common.ufn_SplitString(t1._SubtotalKey,'_') ufn
WHERE t1._ExecRun_UID = #ExecUID AND t1._Scenario = #Scenario
AND t1.t_proj >= 0 AND t1.t_proj <= 650
ORDER BY SubtotalKey, time_period
Here is some sample data for t1:
t_proj SubtotalKey Scenario ExecRun_UID InvExpSCF InvExpReinSCF
1 ABD_1999_MAE_1 1 36FA21C8 5334.44 37.88
2 EMM_E12_MAE_3 1 36FA21C8 1894.88 1298.3
3 XYZ_2008_MAE_1 1 36FA21C8 12.99 10009.33
Here is some sample data for t2:
t_proj SubtotalKey Scenario ExecRun_UID SolvSurvXCF SolvDeathXCF ReinSwap
1 ABD_1999_MAE_1 1 36FA21C8 543.88 12.33 1.2
2 EMM_E12_MAE_3 1 36FA21C8 2985.11 59.31 4.6
3 XYZ_2008_MAE_1 1 36FA21C8 309999.12 111.33 9.7
Here is some sample data for t3:
t_proj SubtotalKey Scenario ExecRun_UID ExpenseValXCF AnnClaimVal DeathClaimVal
1 ABD_1999_MAE_1 1 36FA21C8 100 901 678
2 EMM_E12_MAE_3 1 36FA21C8 200 492 121
3 XYZ_2008_MAE_1 1 36FA21C8 554 510 144
Here is the desired output:
t_proj Col1 Col2 Col3 Col4 Scenario ExecRun_UID InvExpSCF InvExpReinSCF SolvSurvXCF SolvDeathXCF ReinSwap ExpenseValXCF AnnClaimVal DeathClaimVal
1 ABD 1999 MAE 1 1 36FA21C8 5334.44 37.88 543.88 12.33 1.2 100 901 678
2 EMM E12 MAE 1 1 36FA21C8 1894.88 1298.3 2985.11 59.31 4.6 200 492 121
3 XYZ 2008 MAE 1 1 36FA21C8 12.99 10009.33 309999.12 111.33 9.7 554 510 144
Function code:
ALTER FUNCTION [sch_Common].[ufn_SplitString]
(
#Input NVARCHAR(MAX),
#Character CHAR(1)
)
RETURNS #Output TABLE (
Item NVARCHAR(1000)
)
AS
BEGIN
DECLARE #StartIndex INT, #EndIndex INT
SET #StartIndex = 1
IF SUBSTRING(#Input, LEN(#Input) - 1, LEN(#Input)) <> #Character
BEGIN
SET #Input = #Input + #Character
END
WHILE CHARINDEX(#Character, #Input) > 0
BEGIN
SET #EndIndex = CHARINDEX(#Character, #Input)
INSERT INTO #Output(Item)
SELECT SUBSTRING(#Input, #StartIndex, #EndIndex - 1)
SET #Input = SUBSTRING(#Input, #EndIndex + 1, LEN(#Input))
END
RETURN
END
Assuming that You looking something as below (Varibale : ABD_1999_MAE_1):
Column1 Column2 Column3 Column4
ABD 1999 MAE 1
If, above is correct then You could use XML method and CROSS APPLY
SELECT DISTINCT
A.t_proj,
split.a.value('/X[1]', 'NVARCHAR(MAX)') Col1,
split.a.value('/X[2]', 'NVARCHAR(MAX)') Col2,
split.a.value('/X[3]', 'NVARCHAR(MAX)') Col3,
split.a.value('/X[4]', 'NVARCHAR(MAX)') Col4,
A.Scenario,
A.ExecRun_UID,
A.InvExpSCF,
A.InvExpReinSCF,
A.SolvSurvXCF,
A.SolvDeathXCF,
A.ReinSwap,
A.ExpenseValXCF,
A.AnnClaimVal,
A.DeathClaimVal
FROM
(
SELECT T1.t_proj,
CAST('<X>'+REPLACE(T1.SubtotalKey, '_', '</X><X>')+'</X>' AS XML) AS String,
T1.Scenario,
T1.ExecRun_UID,
T1.InvExpSCF,
T1.InvExpReinSCF,
T2.SolvSurvXCF,
T2.SolvDeathXCF,
T2.ReinSwap,
T3.ExpenseValXCF,
T3.AnnClaimVal,
T3.DeathClaimVal
FROM T1
INNER JOIN T2 ON T2.t_proj = T1.t_proj
AND T2.SubtotalKey = T1.SubtotalKey
AND T2.Scenario = T1.Scenario
INNER JOIN T3 ON T3.t_proj = T1.t_proj
AND T3.SubtotalKey = T3.SubtotalKey
AND T3.Scenario = T1.Scenario
) AS A
CROSS APPLY String.nodes('/X') split(a);
Desired Result :
t_proj Col1 Col2 Col3 Col4 Scenario ExecRun_UID InvExpSCF InvExpReinSCF SolvSurvXCF SolvDeathXCF ReinSwap ExpenseValXCF AnnClaimVal DeathClaimVal
1 ABD 1999 MAE 1 1 36FA21C8 5334.44 37.88 543.88 12.33 1.2 100 901 678
2 EMM E12 MAE 3 1 36FA21C8 1894.88 1298.3 2985.11 59.31 4.6 200 492 121
3 XYZ 2008 MAE 1 1 36FA21C8 12.99 10009.33 309999.12 111.33 9.7 554 510 144

SQL query to get multihierarchy items

in my SQL Table i have following data
ID Level Description Code MasterID
1 1 Cars AD0 NULL
2 1 Trucks JF1 NULL
3 1 Items YU2 NULL
4 2 New Cars AS3 1
5 2 Used Cars TG4 1
6 2 Car parts UJ5 1
7 2 New trucks OL6 2
8 2 Used trucks PL7 2
9 2 Truck parts KJL8 2
10 2 Factory stuff UY9 3
11 2 Custom stuff RT10 3
12 3 Toyota 6YH11 4
13 3 BMW 9OKH12 4
14 3 VW 13 5
15 3 Tiers Type I J14 6
16 3 Tiers Type II J15 6
17 3 Tiers Type III ADS16 9
18 3 Seats SA17 6
19 3 Doors UU18 6
20 3 Lights 9OL19 6
21 4 Left light GH20 20
22 4 Right light H21 20
23 4 Left door JHJ22 19
24 4 Michelin UY23 16
25 4 Vredestein GTF24 17
26 4 Dunlop 25 15
My achievement is to get all hierarchy data for each single item. For Exmaple, the outpu should look like as following
ID Level Description Code MasterId1 Description1 MasterId2 Description2 MasterId3 Description3
24 4 Michelin UY23 16 Tiers Type II 6 Car Parts 1 Cars
.
.
19 3 Doors UU18 6 Car Parts 1 Cars NULL NULL
.
.
10 2 Factory Stuff UY9 3 Items NULL NULL NULL NULL
.
.
3 1 Items NULL NULL NULL NULL NULL NULL NULL
.
.
If somebody can help or give an advise how to achieve this?
This is not dynamic but it could be pretty easily.
Using a recursive cte you can get the hierarchy for the entire table and self join a few times to get the table structure you want.
;WITH cte AS
(
SELECT *, ID AS [RootID], 1 AS [MasterLevel] FROM Table1
UNION ALL
SELECT t1.*, cte.[RootID], cte.[MasterLevel] + 1 FROM Table1 t1
JOIN cte ON t1.ID = cte.MasterID
)
SELECT r.ID, r.[Level], r.[Description], r.[Code],
m1.ID AS MasterId1, m1.[Description] AS Description1,
m2.ID AS MasterId2, m1.[Description] AS Description2,
m3.ID AS MasterId3, m1.[Description] AS Description3
FROM cte r
LEFT JOIN cte m1 ON m1.[RootID] = r.[RootID] AND m1.MasterLevel = 2
LEFT JOIN cte m2 ON m2.[RootID] = r.[RootID] AND m2.MasterLevel = 3
LEFT JOIN cte m3 ON m3.[RootID] = r.[RootID] AND m3.MasterLevel = 4
WHERE r.MasterLevel = 1
ORDER BY r.RootID DESC, r.MasterLevel
This would build a dynamic sql to get master and desciption fields based on the maximum Level value. or you could define how many levels you want to see by changing the #MaxLevel
DECLARE #Sql VARCHAR(MAX) = '',
#SelectSql VARCHAR(MAX) = '',
#JoinSql VARCHAR(MAX) = '',
#MaxLevel INT,
#idx INT = 1
SET #MaxLevel = (SELECT MAX([Level]) FROM Table1)
WHILE #idx < #MaxLevel
BEGIN
SET #SelectSql = #SelectSql + REPLACE(', m<index>.ID AS MasterId<index>, m<index>.[Description] AS Description<index> ', '<index>', #idx)
SET #JoinSql = #JoinSql + REPLACE(' LEFT JOIN cte m<index> ON m<index>.[RootID] = r.[RootID] AND m<index>.MasterLevel = <index> ', '<index>', #idx)
SET #idx = #idx + 1
END
SET #Sql = '
;WITH cte AS
(
SELECT *, ID AS [RootID], 0 AS [MasterLevel] FROM Table1
UNION ALL
SELECT t1.*, cte.[RootID], cte.[MasterLevel] + 1 FROM Table1 t1
JOIN cte ON t1.ID = cte.MasterID
)
SELECT r.ID, r.[Level], r.[Description], r.[Code]' + #SelectSql
+ 'FROM cte r ' + #JoinSql
+ 'WHERE r.MasterLevel = 0
ORDER BY r.RootID DESC, r.MasterLevel'
EXEC(#Sql)

Implementing this join in SQL Stored procedure

I have 4 tables Position, Employee, Training and Trmatrix.
Table Position
PositionId PosName TrainingId
1 developer 1,2,3
2 Designer 4,5
3 BDA 2,3,6
Table Employee
Employeeid Ename Posid Courseid
1 Alex 1 4
2 Shaun 2 1,2,3
3 Hales 3
Table Training
Trainingid Trainingname
1 JAVA
2 Dot Net
3 PHP
4 Photoshop
5 JQUERY
6 Client Handling
TrMatrix
TrmatId TrID empID
1 1 1
2 2 1
3 3 1
4 4 1
5 4 2
6 5 2
7 1 2
8 2 2
9 2 3
10 3 3
foreign Key relation
trmatrix trId corresponds to the trainingID of the trainingtable.
Employee posid corresponds to the PositionId of the Positiontable.
Employee courseId corresponds to the trainingId of the trianingtable.
BY basic Aim is to get that course/trainingname which is no present in the
EMployee.Courseid column in correspondance to the trmatrix table,
which defines that I have to get the all entries from the trmatrix table for which there is no entry in the employee table Courseid column.
Suppose in case of Alex I have to fetch all the data from the trmatrix table except for course 4 since it is present in the courseid column of the Employee table, so it would return course no 1,2,3 not the no 4.
I am Newbie to the SQL so please help me out with this problem.
Thanks in advance
To start with, you should make PositionTraining and EmployeeCourse tables as well:
PositionTraining
PositionId TrainingId
1 1
1 2
1 3
2 4
2 5
3 2
3 3
3 6
EmployeeCourse
Employeeid Courseid
1 4
2 1
2 2
3 3
and then remove Position.TrainingId and Employee.Courseid.
By doing this you make the data much easier to query.
To get things which are not present in one table from another you can use
WHERE NOT EXISTS (SELECT value FROM OtherTable)
or
WHERE NOT IN (SELECT value FROM OtherTable)
However there is a class of queries called subqueries and these are very useful in this circumstance and a very good article on them is here
http://allenbrowne.com/subquery-01.html
(its written for ms access but the synstax and MS SQL rules are exactly the same so dont be put off)
UDF for spliting out entries
Create function [dbo].[atf_BarListToTable]
(#list ntext)
RETURNS #tbl TABLE (ListPosn int IDENTITY(1, 1) NOT NULL,
SString VARCHAR(1028) NOT NULL) AS
BEGIN
DECLARE #pos int
DECLARE #textpos int
DECLARE #ChunkLength smallint
DECLARE #str nvarchar(4000)
DECLARE #tmpstr nvarchar(4000)
DECLARE #leftover nvarchar(4000)
SET #textpos = 1
SET #leftover = ''
WHILE #textpos <= datalength(#list) / 2
BEGIN
SET #ChunkLength = 4000 - datalength(#leftover) / 2
SET #tmpstr = ltrim(#leftover + substring(#list, #textpos, #ChunkLength))
SET #textpos = #textpos + #ChunkLength
SET #pos = charindex('|', #tmpstr)
WHILE #pos > 0
BEGIN
SET #str = substring(#tmpstr, 1, #pos - 1)
INSERT #tbl (SString) VALUES( #str)
SET #tmpstr = ltrim(substring(#tmpstr, #pos + 1, len(#tmpstr)))
SET #pos = charindex('|', #tmpstr)
END
SET #leftover = #tmpstr
END
IF ltrim(rtrim(#leftover)) <> ''
INSERT #tbl (SString) VALUES(#leftover)
RETURN
END