如何在sql中过滤临时表

时间:2016-12-07 12:05:53

标签: sql sql-server

我创建了一个存储过程并将列存储在名为@Temp的临时表中。我想立即根据列中的值过滤@Temp临时表。

BEGIN
DECLARE @ActivityId INT
    DECLARE @NM AS DATE
    DECLARE @Tmp VARCHAR(50)
    DECLARE @Temp AS TABLE (
        MachineName VARCHAR(500)
        ,ActivityName VARCHAR(500)
        ,NM DATE
        )

    DECLARE Temcur1 CURSOR
    FOR
    SELECT *
    FROM (
        SELECT ActivityId
            ,MachineId
            ,[NextMaintenance] = dbo.udf_GetDateOnFrequency(CreatedOn, Frequency, Frequency_Unit)
        FROM activity_master
        WHERE Frequency_Unit > 0
            AND (
                Frequency <> ''
                OR Frequency <> '&nbsp;'
                )
        ) T
    WHERE [NextMaintenance] >= cast(@StartDate AS DATE)
        AND [NextMaintenance] <= cast(@EndDate AS DATE)

    OPEN Temcur1

    FETCH Temcur1
    INTO @ActivityId
        ,@machineID
        ,@NM

    WHILE @@Fetch_Status = 0
    BEGIN
        DECLARE Temp1 CURSOR
        FOR
        SELECT Item
        FROM dbo.udf_cmn_split(@MachineId, ',')

        OPEN Temp1

        FETCH Temp1
        INTO @Tmp

        WHILE @@Fetch_Status = 0
        BEGIN
            INSERT INTO @Temp
            SELECT [m] = (
                    SELECT Machine_Name
                    FROM machine_master
                    WHERE machine_Id = @Tmp
                    )
                ,[a] = (
                    SELECT ActivityName
                    FROM activity_master
                    WHERE Activityid = @ActivityId
                    )
                ,@NM

            FETCH Temp1
            INTO @Tmp
        END

        CLOSE Temp1

        DEALLOCATE Temp1

        FETCH Temcur1
        INTO @ActivityId
            ,@machineID
            ,@NM
    END

    CLOSE Temcur1

    DEALLOCATE Temcur1

    --select Machine_Name, am.ActivityName,Replace(Convert(varchar,CAST(NextMaintenanceDate As date),106),' ','-')[NM] from Maintenance_Activity m inner join Machine_Master mm on m.MachineId = mm.Machine_Id 
    --inner join Activity_Master am on m.ActivityId=am.ActivityId where Completed_Status='PENDING'
    --and [NextMaintenanceDate]>cast(getdate()-7 as date)
    --and [NextMaintenanceDate]<cast(getdate()+7 as date)
    --Union  
    SELECT MachineName
        ,ActivityName
        ,Replace(Convert(VARCHAR, CAST(NM AS DATE), 106), ' ', '-') NM
    FROM @Temp
    WHERE MachineName = @MachineID
END

在上面的代码中,我可以用

选择值
SELECT MachineName
,ActivityName
,Replace(Convert(VARCHAR, CAST(NM AS DATE), 106), ' ', '-') NM
FROM @Temp

但如果我给出条件

SELECT MachineName
,ActivityName
,Replace(Convert(VARCHAR, CAST(NM AS DATE), 106), ' ', '-') NM
FROM @Temp
WHERE MachineName = @MachineID

它没有返回任何列。

提前致谢

0 个答案:

没有答案