在SQL Server 2012中的表值函数中使用表变量时出现语法错误

时间:2015-11-06 15:52:37

标签: sql sql-server tsql sql-server-2012

我正在尝试将表变量与表值函数一起使用,但是我收到了语法错误。请帮我解决这个问题。

以下是代码:

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

我收到此错误

  

带有返回值的RETURN语句不能在此上下文中使用。

1 个答案:

答案 0 :(得分:0)

如果您想使用您的功能,请使用下面的工作版本。但是有更好的解决方案,请参阅:

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

或尝试类似的事情:

def create
  @post = Post.new
  @post.content = params["content"]
  @post.user_id = params["user"]["user_id"];

  @post.save!
end