2013-03-13 80 views
0

我已經在sql server中創建了一個表值函數,並且我在變量中存儲了一個'select'statemetn作爲傳遞變量的遊標聲明,它顯示我錯誤。在遊標聲明處傳遞一個變量爲「select」語句的可能性

我的錯誤是

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 [email protected]_DAY + 1 
    SET @QUERY='SELECT A.NAME, ' 
    SET @COUNT_TEST = 1 
WHILE @COUNT_TEST <= @COUNT 
BEGIN 
    IF(@COUNT_TEST [email protected]) 
     SET @[email protected] + 'B.D' + CONVERT(NVARCHAR ,@START_DAY) 
ELSE 
    SET @[email protected] + 'B.D' + CONVERT(NVARCHAR ,@START_DAY) + ', ' 
SET @START_DAY = @START_DAY + 1 
SET @COUNT_TEST [email protected]_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

[在存儲過程中使用動態SQL遊標]的可能重複(HTTP select語句://stackoverflow.com/questions/1045880/using-a-cursor-with-dynamic-sql-in-a-stored-procedure) – cfeduke 2013-03-14 00:12:40

回答

0

你不能以這種方式聲明遊標。您必須編寫select語句,而不是使用select語句字符串傳遞變量。

請參閱文檔以獲取更多信息。 DECLARE CURSOR (Transact-SQL)

0

嘗試再進行一次臨時表和光標之前執行你的@QUERY比寫光標和臨時表