Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Error handling within a function

Author  Topic 

hya
Starting Member

1 Post

Posted - 2007-06-26 : 05:28:18
I'd like to write a function which splits a string in Original table by comma, inserts the splitted recodes into Result table, and inserts the invalid recodes into Reject table.

I wrote the code listed below but doesn't work.
Can anyone tell me how to manage this on SQL Server 2000?


---
CREATE FUNCTION
SplitByComma()
RETURNS
@tblResult TABLE
(
COL1 nvarchar(20)
,COL2 nvarchar(20)
,COL3 nvarchar(20)
)
AS
BEGIN
DECLARE @curTbl cursor
DECLARE @strCOL nvarchar(100)
DECLARE @strCOL1 nvarchar(20)
DECLARE @strCOL2 nvarchar(20)
DECLARE @strCOL3 nvarchar(20)
DECLARE @strDlm char(1)
DECLARE @intOffset int
DECLARE @intLen int

SET @strDlm = ','

SET @curTbl = CURSOR FOR SELECT COL FROM OriginalTable
OPEN @curTbl
FETCH NEXT FROM @curTbl INTO @strCOL
WHILE @@FETCH_STATUS = 0
BEGIN
SET @intOffset = 1;
SET @intLen = charindex(@strDlm, @strCOL) - 1
IF @intLen < 0 GOTO BAD_RECODE
SET @strCOL1 = substring(@strCOL, @intOffset, @intLen)

SET @intOffset = @intOffset + @intLen + 1
SET @intLen = charindex(@strDlm, @strCOL, @intOffset) - @intOffset
IF @intLen < 0 GOTO BAD_RECODE
SET @strCOL2 = substring(@strCOL, @intOffset, @intLen)

SET @intOffset = @intOffset + @intLen + 1
SET @intLen = charindex(@strDlm, @strCOL, @intOffset) - @intOffset
IF @intLen < 0 GOTO BAD_RECODE
SET @strCOL3 = substring(@strCOL, @intOffset, @intLen)

INSERT INTO @tblResult SELECT @strCOL1, @strCOL2, @strCOL3
GOTO GOOD_RECODE

BAD_RECODE:
INSERT INTO RejectTable SELECT @strCOL -- ERROR!!

GOOD_RECODE:
FETCH NEXT FROM @curTbl INTO @strCOL
END
CLOSE @curTbl

RETURN
END

---

ex)

OriginalTable
+----------+
|COL |
+----------+
|A1,B1,C1 |
|A2,B2,C2 |
|A3,B3 |
+----------+

ResultTable
+----+----+----+
|COL1|COL2|COL3|
+----+----+----+
|A1 |B1 |C1 |
|A2 |B2 |C2 |
+----+----+----+

RejectTable
+----------+
|COL |
+----------+
|A3,B3 |
+----------+

   

- Advertisement -