开发者

Incorrect syntax in IF body

开发者 https://www.devze.com 2023-03-22 12:54 出处:网络
I try to create this function which concatenates all rows into one string: CREATE function [dbo].[fn_GetProjectDevelopers] (

I try to create this function which concatenates all rows into one string:

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

I get these errors:

Incorrect syntax near '@DevList'.
I开发者_运维百科ncorrect syntax near the keyword 'CLOSE'.
Incorrect syntax near 'end'.

It's the @DevList in the BEGIN ... END part in the IF body.


The error is this

 @DevList = @DevName+ ' ' + @DevList

should be this

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

Your other problem is

DECLARE @DevList varchar

Where is the size? that will only be 1 character!!

however there are better ways to do this

Here is a way without a cursor

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

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

SELECT @DevList

Runnable example

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

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

SELECT @DevList


You're missing the SET from the IF statement :)

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


You are missing the SET keyword:

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

精彩评论

暂无评论...
验证码 换一张
取 消