简体   繁体   English

如何在SQL SERVER 2005中使用递归表值函数

[英]How to use recursive table valued function in SQL SERVER 2005

I am making a split function in SQL Server 2005. 我在SQL Server 2005中创建拆分功能。

I have already done it by using a while loop . 我已经通过使用while循环做到了。

But I am not happy with that. 但是我对此不满意。 I want to do it using recursive function. 我想使用递归函数。

I have already done it in C#. 我已经用C#完成了。 Now I am plotting the same in SQL SERVER 2005. But I am getting a compilation error. 现在,我在SQL SERVER 2005中绘制了相同的图形。但是却遇到了编译错误。

Here is my code 这是我的代码

ALTER FUNCTION [dbo].[fnSplit2] 
(

    @OLDSTRING AS VARCHAR(100),
    @DELIMETER AS VARCHAR(1)
)

RETURNS @MYTABLE TABLE(COUNTER INT,STRINGVAL VARCHAR(100)) 
    AS
        Begin 

            DECLARE @NEWSTRING AS VARCHAR(100)
            DECLARE @POS AS INT
            DECLARE @LEN AS INT
            DECLARE @COUNTER AS INT 

            SET @NEWSTRING = '';        
            SET @LEN = LEN(@OLDSTRING)
            SET @COUNTER = 0
            SET @POS = CHARINDEX(@DELIMETER, @OLDSTRING) 

            IF(@POS > 0)

                BEGIN 

                    SET @COUNTER = @COUNTER +1

                    INSERT INTO @MYTABLE(COUNTER,STRINGVAL) VALUES(@COUNTER,@NEWSTRING + SUBSTRING(@OLDSTRING,0, @POS))
                    SET @OLDSTRING = SUBSTRING(@OLDSTRING,0, @POS)
                    fnSplit2(@OLDSTRING,@DELIMETER);

                END

            ELSE

                BEGIN
                    SET @COUNTER = @COUNTER +1
                    INSERT INTO @MYTABLE(COUNTER,STRINGVAL) values(@COUNTER,@OLDSTRING)
                END

    RETURN
END

The ERROR is: Msg 102, Level 15, State 1, Procedure fnSplit2, Line 38 Incorrect syntax near 'fnSplit2'. 错误是:消息102,级别15,状态1,过程fnSplit2,第38行'fnSplit2'附近的语法不正确。

Cannot I use a recursive table valued function in SQL SERVER ? 我不能在SQL SERVER中使用递归表值函数吗?

I searched in the google and found that Scalar valued recursive functions are possible? 我在谷歌搜索,发现标量值的递归函数是可能的吗?

Please provided the code and at the same time tell me the mistake that I am making. 请提供代码,同时告诉我所犯的错误。

Appreciate for any help! 感谢您的帮助!

Answer: 回答:

You're calling fnSplit2 in the wrong way. 您以错误的方式调用fnSplit2。 A table valued function is exactly that: a "table"... it goes where a "real" table would go in a FROM clause. 表值函数的确切含义是:“表” ...在FROM子句中可以到达“实际”表的位置。

Comment: 评论:

If you really must split CSVs in SQL, read Erland Sommarskog's article on various ways to do it properly. 如果您真的必须在SQL中拆分CSV,请阅读Erland Sommarskog的文章 ,以了解各种正确执行方法。 Note he does not list a recursive TVF method... 请注意,他没有列出递归TVF方法...

Also, you probably need to use the schema name in the reference as well: "dbo.fnSplit2(..)". 另外,您可能还需要在引用中使用架构名称:“ dbo.fnSplit2(..)”。 And as previously mentioned, use it as a table reference. 并且如前所述,将其用作表参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM