我在sql server中创建了一个值为funciton的表,并且我在变量中存储了一个'select'statemetn作为在游标声明中传递变量,它显示了我的错误。
我的错误是
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
答案 0 :(得分:0)
您不能以这种方式声明游标。您必须编写select语句,而不是使用select语句字符串传递变量。
从更多信息中查看文档。 的 DECLARE CURSOR (Transact-SQL) 强>
答案 1 :(得分:0)
尝试创建另一个临时表并在游标之前执行@QUERY而不是使用临时表中的select语句写入游标