IF正文中的语法不正确

时间:2011-07-22 17:38:17

标签: tsql sql-server-2008

我尝试创建这个函数,将所有行连接成一个字符串:

CREATE function [dbo].[fn_GetProjectDevelopers] ( 
  @ProjectId         varchar(100)
)
returns varchar
as
begin

DECLARE @DevList varchar

DECLARE @DevName varchar(50)
SET @DevList = '';
DECLARE my_cursor CURSOR FOR
SELECT DISTINCT ServiceAppointment.OwnerIdName as Name 
                    FROM ServiceAppointment

OPEN my_cursor

FETCH NEXT FROM my_cursor INTO @DevName 

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @DevName NOT LIKE '%' + @DevList +  '%'
        BEGIN
            @DevList = @DevName+ ' ' + @DevList
        END
    FETCH NEXT FROM my_cursor INTO @DevName
END

CLOSE my_cursor
DEALLOCATE my_cursor


  return @DevList
end

我收到这些错误:

Incorrect syntax near '@DevList'.
Incorrect syntax near the keyword 'CLOSE'.
Incorrect syntax near 'end'.

它是IF体中BEGIN ... END部分的@DevList。

3 个答案:

答案 0 :(得分:1)

您错过了IF语句中的SET:)

BEGIN
IF @DevName NOT LIKE '%' + @DevList +  '%'
    BEGIN
        SET @DevList = @DevName+ ' ' + @DevList
    END
FETCH NEXT FROM my_cursor INTO @DevName
END

答案 1 :(得分:1)

错误就是这个

 @DevList = @DevName+ ' ' + @DevList

应该是这个

SET  @DevList = @DevName+ ' ' + @DevList

你的另一个问题是

DECLARE @DevList varchar

尺寸在哪里?这只会是1个角色!!

但是有更好的方法可以做到这一点

这是一种没有光标的方法

DECLARE @DevList varchar(8000)
SET @DevList = '';

SELECT   @DevList = @DevList +  OwnerIdName + ' '
from (select distinct OwnerIdName 
                    FROM ServiceAppointment where OwnerIdName  is not null ) x 

SELECT @DevList

可运行的示例

DECLARE @DevList varchar(8000)
SET @DevList = '';

SELECT   @DevList = @DevList +  name + ' '
from (select distinct name  FROM sysobjects) x 

SELECT @DevList

答案 2 :(得分:0)

您错过了SET关键字:

SET @DevList = @DevName+ ' ' + @DevList