拆分功能获取错误

时间:2012-01-30 20:51:48

标签: sql-server sql-server-2005 sql-server-2000

下面的代码我用于MSSQL 2005,但是当我尝试在MSSQL 2000中运行时,我正在使用以下错误。

Msg 156, Level 15, State 1, Procedure StrSplit, Line 5
Incorrect syntax near the keyword 'WITH'.
Msg 170, Level 15, State 1, Procedure StrSplit, Line 15
Line 15: Incorrect syntax near ')'.

CREATE FUNCTION dbo.StrSplit (@sep char(1), @s varchar(512))  
    RETURNS table  
    AS  
    RETURN (  
        WITH Pieces(pn, start, stop) AS (  
          SELECT 1, 1, CHARINDEX(@sep, @s)  
          UNION ALL  
          SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)  
          FROM Pieces  
          WHERE stop > 0  
        )  
        SELECT pn,  
          SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s  
        FROM Pieces  
      )

提前致谢

3 个答案:

答案 0 :(得分:1)

CTE - IE“WITH”是从sql 2005开始的一项功能。2000年不可用...

答案 1 :(得分:1)

您不能在SQL Server 2000中使用CTE(Common Table Expressions - WITH)。它们是在SQL Server 2005中引入的。

答案 2 :(得分:1)

在其位置使用以下功能。

CREATE  FUNCTION [dbo].[fn_Split](@text VARCHAR(8000), @delimiter VARCHAR(20) = ' ')
RETURNS @Strings TABLE
(    
  position int IDENTITY PRIMARY KEY,
  value varchar(8000)   
)
AS

BEGIN
DECLARE @index int 

SET @text = LTRIM(RTRIM(@text))

SET @index = -1 
WHILE (LEN(@text) > 0) 
 BEGIN  
    SET @index = CHARINDEX(@delimiter , @text)  
    IF (@index = 0) AND (LEN(@text) > 0)  
      BEGIN   
        INSERT INTO @Strings VALUES (@text)
          BREAK  
      END  
    IF (@index > 1)  
      BEGIN   
        INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))   
        SET @text = RIGHT(@text, (LEN(@text) - @index))  
      END  
    ELSE 
      SET @text = RIGHT(@text, (LEN(@text) - @index)) 
    END
  RETURN
END

希望这会有所帮助!!