我的查询给出了结果集,但我无法使用该查询创建过程

时间:2017-05-16 11:03:25

标签: sql-server sql-server-2008 stored-procedures

我使用Cursor创建了一个查询。它给出了结果集。但是如果我尝试将它创建为'Procedure'。它会抛出错误'无效的列名'。

产生结果的My Piece Of查询:

DECLARE @ContactID INT, @ActivityID INT, @RecurrencePattern INT, @Day   VARCHAR(50), @DayPattern VARCHAR(50), @Month INT, @StartDate DATETIME, @EndDate DATETIME, @Frequency VARCHAR(50),

DECLARE db_cursor CURSOR FOR  
SELECT RT.ContactID, RT.ActivityID, F.Frequency, RT.RecurrencePattern, RT.Day, RT.DayPattern, RT.Month, RT.StartDate, ISNULL(RT.EndDate, 
    DATEADD(MONTH,((YEAR(DATEADD(MONTH, 3, GETDATE())) - 1900) * 12) + MONTH(DATEADD(MONTH, 3, GETDATE())),-1)) AS EndDate
FROM tblrecurringtasks RT
    INNER JOIN luFrequency F ON F.FrequencyID = RT.FrequencyID
WHERE RT.TaskID = xx ;

SET QUOTED_IDENTIFIER OFF 

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @ContactID, @ActivityID, @Frequency, @RecurrencePattern, @Day, @DayPattern, @Month, @StartDate, @EndDate
WHILE @@FETCH_STATUS = 0 
BEGIN 
SET @Running_date = @StartDate;
SET @temp_Date = @StartDate;
DECLARE @RPattern INT = 0;
WHILE @Running_date <= @EndDate
BEGIN
    DECLARE @WeekDay INT = DATEPART(dw, @Running_date)

    IF @Frequency = "Daily"
    BEGIN   
        BEGIN
            BEGIN
                PRINT 'X'
                  BREAK
                END
                SET @DayList = STUFF(@DayList, 1, CHARINDEX(',', @DayList+','), '')
            END
        END
        ELSE
        BEGIN
            BEGIN
               PRINT 'y'
                SET @temp_Date = @temp_Date + @RecurrencePattern
            END
        END
    END

我的选择查询将频率结果生成为“每日”。因此查询适用于我。但是,如果我尝试创建这样的程序,

CREATE PROCEDURE [dbo].[sp_InsertRecurringTasks]
@TaskID int
AS 
BEGIN
SET NOCOUNT ON;
*/  Above query */
END

它会抛出错误无效的列名称'Daily'。 什么可能是问题。解决它。请帮助我。谢谢你。

1 个答案:

答案 0 :(得分:0)

您不应该使用双引号检查字符串,以下代码将给出相同的错误:

DECLARE @Frequency NVARCHAR(4);

SELECT @Frequency = 'Test';

IF @Frequency = 'Test'
PRINT 'Yes';

在哪里,这将起作用:

a