0

我已经在 sql server 中创建了一个表值函数,并且我在变量中存储了一个“选择”状态作为游标声明处的传递变量,它向我显示错误。

我的错误是

Incorrect syntax near '@QUERY'.

我的功能是

CREATE FUNCTION WEEKLY_REPORT(@START_DATE DATETIME, @END_DATE DATETIME,@PRACTISE NVARCHAR(MAX))
RETURNS @WEEKLY_REPORT_DETAILS_INFORMATION TABLE
(
    RESOURCE_NAME NVARCHAR(MAX),
    DAY1 DECIMAL(5,2),
    DAY2 DECIMAL(5,2),
    DAY3 DECIMAL(5,2),
    DAY4 DECIMAL(5,2),
    DAY5 DECIMAL(5,2),
    DAY6 DECIMAL(5,2),
    DAY7 DECIMAL(5,2),
    UTILIZATION INT
)
AS 
BEGIN
DECLARE
    @RESOURCE_NAME NVARCHAR(MAX),
    @DAY1 DECIMAL(5,2),
    @DAY2 DECIMAL(5,2),
    @DAY3 DECIMAL(5,2),
    @DAY4 DECIMAL(5,2),
    @DAY5 DECIMAL(5,2),
    @DAY6 DECIMAL(5,2),
    @DAY7 DECIMAL(5,2),
    @UTILIZATION INT,
    @MONTH NVARCHAR(MAX),
    @START_DAY INT,
    @END_DAY INT,
    @COUNT INT,
    @COUNT_TEST INT,
    @QUERY NVARCHAR(MAX);
BEGIN
    SET @MONTH = DATENAME(MONTH,@START_DATE)
    SET @START_DAY = DATENAME(DAY,@START_DATE)
    SET @END_DAY = DATENAME(DAY,@END_DATE)
    SET @COUNT = @END_DAY -@START_DAY + 1
    SET @QUERY='SELECT A.NAME, '
    SET @COUNT_TEST = 1
WHILE @COUNT_TEST <= @COUNT
BEGIN
    IF(@COUNT_TEST =@COUNT)
        SET @QUERY=@QUERY + 'B.D' + CONVERT(NVARCHAR ,@START_DAY)
ELSE
    SET @QUERY=@QUERY + 'B.D' + CONVERT(NVARCHAR ,@START_DAY) + ', ' 
SET @START_DAY = @START_DAY + 1
SET @COUNT_TEST =@COUNT_TEST + 1 
END

SET @QUERY = @QUERY + ' FROM EMPLOYEE A INNER JOIN CP_DETAILS B' +
            ' ON A.ID = B.EMPLOYEE_ID WHERE B.MONTH_USED = ' + '''' + @MONTH     + '''' +
            ' AND B.YEAR_USED = ' + DATENAME(YEAR,@START_DATE) + 
            ' AND B.PRACTISE=' + '''' + @PRACTISE + ''''

DECLARE CP_DETAILS CURSOR FOR @QUERY-- facing error here

OPEN CP_DETAILS
FETCH NEXT FROM CP_DETAILS INTO @RESOURCE_NAME,@DAY1,@DAY2,@DAY3,@DAY4,@DAY5,@DAY6,@DAY7

WHILE (@@FETCH_STATUS =0)
BEGIN
    SET @UTILIZATION = dbo.UTILIZATION(@START_DATE,@END_DATE,@DAY1,
                                    @DAY2,@DAY3,@DAY4,@DAY5,@DAY6,@DAY7)
    INSERT INTO @WEEKLY_REPORT_DETAILS_INFORMATION VALUES(@RESOURCE_NAME,
                @DAY1,@DAY2,@DAY3,@DAY4,@DAY5,@DAY6,@DAY7,@UTILIZATION)

    FETCH NEXT FROM CP_DETAILS INTO @RESOURCE_NAME,@DAY1,@DAY2,@DAY3,@DAY4,@DAY5,@DAY6,@DAY7
END
CLOSE CP_DETAILS
DEALLOCATE CP_DETAILS
END
RETURN 

END
4

2 回答 2

0

您不能以这种方式声明游标。您必须编写 select 语句,而不是使用 select 语句字符串传递变量。

请参阅更多信息中的文档。 声明游标 (Transact-SQL)

于 2013-03-13T12:47:08.520 回答
0

尝试创建另一个临时表并在游标之前执行您的@QUERY,而不是使用临时表中的 select 语句写入游标

于 2013-03-13T14:54:03.523 回答