将存储过程数据插入临时表不起作用

Posted

技术标签:

【中文标题】将存储过程数据插入临时表不起作用【英文标题】:Insert stored procedure data into temp table not working 【发布时间】:2016-03-15 11:35:46 【问题描述】:

我创建了一个带有 3 个参数的存储过程。见下文

ALTER PROCEDURE [dbo].[Leave_Allocation_Mar_2016]
    @Type nvarchar(10),
    @Month int,
    @Year int
AS
BEGIN
    declare @emp_card_no numeric(9)
    declare @emp_name varchar(20)
    declare @dt_of_join datetime
    declare @Total_days numeric(5,2)
    declare @Days_worked numeric(5,2)
    declare @Final_PaidDayLop numeric(5,2)
    declare @TotalRecord int
    declare @actualMonth int
    declare @actualYear int
    declare @actuallastdate varchar(20)     
 IF(@Type = 'C')
BEGIN
            Print 'Yes I am in the Current process';                        
        DECLARE daily_Allocate CURSOR FOR  
                Select distinct c.emp_card_no, c.emp_name, c.Dt_Of_Join from emp_mst c  
                    join emp_mon_day d 
                    on c.emp_card_no=d.emp_mkey 
                    WHERE Dt_Of_Join =  CAST(FLOOR(CAST( DATEADD(month, -6, GETDATE()) AS FLOAT ))AS DATETIME)                  
            OPEN daily_Allocate   
            FETCH NEXT FROM daily_Allocate INTO
            @emp_card_no, @emp_name, @Dt_Of_Join                
            WHILE @@FETCH_STATUS = 0   
            BEGIN                                           
                    select  @Total_days = Sum(total_day),@Days_worked = Sum(days_worked)
                    from emp_mon_day a      
                    where  a.emp_mkey = 2519
                    group by emp_mkey                               
                        PRINT 'Employee Card no = ' + cast(@emp_card_no as char)
                        PRINT 'Total days = ' + cast(@Total_days as char)
                        PRINT 'Days Worked = ' +    cast(@Days_worked as char)                  
                set @Final_PaidDayLop = 0;
                set @TotalRecord = 0;       

                 Select @Final_PaidDayLop =  
                    isnull(sum(days),0)
                    from  P_Emp_Del_App_Hdr c join P_Emp_Del_App_trl d on c.mkey=d.mkey       
                    where c.delete_flag='N' and app_flag='Y' and c.year = @actualYear
                   and c.emp_mkey = @emp_card_no              

            Select @TotalRecord =  ((1.75 * 6) / @Total_days) * (@Days_worked + @Final_PaidDayLop) 
                from emp_mon_day a where  a.emp_mkey = @emp_card_no group by a.emp_mkey                         

        PRINT 'Final Paid LOP '  + cast(coalesce(@Final_PaidDayLop,0) as char)  
        PRINT 'Total Record ' + cast(coalesce(@TotalRecord,0) as char)                  

                  FETCH NEXT FROM daily_Allocate INTO 
                  @emp_card_no, @emp_name, @Dt_Of_Join 
            END   
        CLOSE daily_Allocate   
        DEALLOCATE daily_Allocate
END     END

这给了我如下输出

现在我想要的是,我想将上面的数据插入到临时表中。

我尝试如下

CREATE TABLE #tmp1111
(
  Sr_no int identity(1,1),
   Current_Status nvarchar(255),
   Emp_card_no int,
   Total_days int,
   days_worked int,
   final_lop_paid int,
   total_record int
)

首先我创建了一个临时表并尝试插入如下数据

INSERT INTO #tmp1111 exec Leave_Allocation_Mar_2016 'C', '2', '2016'

它执行成功,但是当我运行 select 语句时,临时表中没有记录。

我正在使用 SQL server 2005

【问题讨论】:

存储过程没有直接输出,只有变量的打印。您需要返回正在打印的这些项目,可能作为 SELECT @VarName。但是不清楚您在寻找什么,因为光标内可能有多个这些? @Paddy:我只想将记录插入到临时表中,这是通过在存储过程中打印得到的。如果除了打印之外我将值插入到表中然后让我知道..希望你现在清楚 为什么要从外部执行存储过程?如果只需要这些参数,则传递到存储过程 【参考方案1】:

代替@Result 表变量使用如下:

CREATE TABLE #Results
(
   Emp_card_no      NUMERIC(9),
   Total_days       NUMERIC(5,2),
   Days_worked      NUMERIC(5,2),
   Final_PaidDayLop NUMERIC(5,2),
   TotalRecord      INT
)

INSERT INTO #Results
( 
    Emp_card_no,
    Total_days,
    Days_worked,
    Final_PaidDayLop
)
VALUES  
( 
    @emp_card_no ,      -- Emp_card_no - numeric
    @Total_days ,       -- Total_days - numeric
    @Days_worked ,      -- Days_worked - numeric
    @Final_PaidDayLop   -- Final_PaidDayLop - numeric
)

在 DEALLOCATE daily_Allocate 之后插入语句

SELECT * FROM #Results
DROP TABLE #Results

此select语句返回执行游标时在#Results临时表中插入记录的所有行

进行这些更改,希望这对您有所帮助

更新:

ALTER PROCEDURE [dbo].[Leave_Allocation_Mar_2016]
    @Type   NVARCHAR(10),
    @Month  INT,
    @Year   INT
AS
BEGIN
    SET NOCOUNT ON;

    CREATE TABLE #Results
    (
       Emp_card_no      NUMERIC(9),
       Total_days       NUMERIC(5,2),
       Days_worked      NUMERIC(5,2),
       Final_PaidDayLop NUMERIC(5,2),
       TotalRecord      INT
    )

    DECLARE @emp_card_no        NUMERIC(9)
    DECLARE @emp_name           VARCHAR(20)
    DECLARE @dt_of_join         DATETIME
    DECLARE @Total_days         NUMERIC(5,2)
    DECLARE @Days_worked        NUMERIC(5,2)
    DECLARE @Final_PaidDayLop   NUMERIC(5,2)
    DECLARE @TotalRecord        INT
    DECLARE @actualMonth        INT
    DECLARE @actualYear         INT
    DECLARE @actuallastdate     VARCHAR(20)     

    IF(@Type = 'C')
    BEGIN

        PRINT 'Yes I am in the Current process';                        

        DECLARE daily_Allocate CURSOR 
        LOCAL SCROLL STATIC
        FOR        
        SELECT DISTINCT c.emp_card_no, c.emp_name, c.Dt_Of_Join FROM emp_mst c  
        JOIN emp_mon_day d ON c.emp_card_no=d.emp_mkey 
        WHERE Dt_Of_Join = 
        CAST(FLOOR(CAST( DATEADD(month, -6, GETDATE()) AS FLOAT)) AS DATETIME)                  

        OPEN daily_Allocate   
        FETCH NEXT FROM daily_Allocate INTO @emp_card_no, @emp_name, @Dt_Of_Join                

        WHILE @@FETCH_STATUS = 0   
        BEGIN                                           
            SELECT @Total_days = SUM(total_day), @Days_worked = SUM(days_worked)
            FROM emp_mon_day a      
            WHERE a.emp_mkey = 2519
            GROUP BY emp_mkey                               

            PRINT 'Employee Card no = ' + cast(@emp_card_no AS CHAR)
            PRINT 'Total days = ' + cast(@Total_days AS CHAR)
            PRINT 'Days Worked = ' + cast(@Days_worked AS CHAR)                  

            SET @Final_PaidDayLop = 0;
            SET @TotalRecord = 0;       

            SELECT @Final_PaidDayLop = ISNULL(SUM(days), 0)
            FROM  P_Emp_Del_App_Hdr c JOIN P_Emp_Del_App_trl d ON c.mkey=d.mkey       
            WHERE c.delete_flag='N' AND app_flag='Y' AND c.year = @actualYear 
            AND c.emp_mkey = @emp_card_no              

            SELECT 
            @TotalRecord = ((1.75 * 6) / @Total_days) * (@Days_worked + @Final_PaidDayLop) 
            FROM emp_mon_day a 
            WHERE  a.emp_mkey = @emp_card_no 
            GROUP BY a.emp_mkey                         

            PRINT 'Final Paid LOP '  + CAST(COALESCE(@Final_PaidDayLop, 0) AS CHAR)  
            PRINT 'Total Record ' + CAST(COALESCE(@TotalRecord, 0) AS CHAR)                  

            INSERT INTO #Results
            ( 
                Emp_card_no,
                Total_days,
                Days_worked,
                Final_PaidDayLop
            )
            VALUES  
            ( 
                @emp_card_no ,      -- Emp_card_no - numeric
                @Total_days ,       -- Total_days - numeric
                @Days_worked ,      -- Days_worked - numeric
                @Final_PaidDayLop   -- Final_PaidDayLop - numeric
            )

        FETCH NEXT FROM daily_Allocate INTO @emp_card_no, @emp_name, @Dt_Of_Join 
        END   

        CLOSE daily_Allocate   
        DEALLOCATE daily_Allocate

        SELECT * FROM #Results
        DROP TABLE #Results

    END     
END

然后EXEC Leave_Allocation_Mar_2016 'C', '2', '2016'你将在表格输出中得到结果

【讨论】:

是的,您可以根据需要添加更多参数 在执行存储过程时,您肯定会得到所有插入到#Result 表中的记录。 让我们continue this discussion in chat。【参考方案2】:

存储过程没有直接输出,只有变量打印。您需要返回所需的值,例如在表格内:

请注意,该表是必需的,而不仅仅是返回变量,因为您的光标内可能有多个循环

ALTER PROCEDURE [dbo].[Leave_Allocation_Mar_2016]
    @Type nvarchar(10),
    @Month int,
    @Year int
AS
BEGIN
    DECLARE @Results TABLE (
       Emp_card_no NUMERIC(9),
       Total_days NUMERIC(5,2),
       Days_worked NUMERIC(5,2),
       Final_PaidDayLop numeric(5,2)
       TotalRecord int
    )

    declare @emp_card_no numeric(9)
    declare @emp_name varchar(20)
    declare @dt_of_join datetime
    declare @Total_days numeric(5,2)
    declare @Days_worked numeric(5,2)
    declare @Final_PaidDayLop numeric(5,2)
    declare @TotalRecord int
    declare @actualMonth int
    declare @actualYear int
    declare @actuallastdate varchar(20)     
 IF(@Type = 'C')
BEGIN
            Print 'Yes I am in the Current process';                        
        DECLARE daily_Allocate CURSOR FOR  
                Select distinct c.emp_card_no, c.emp_name, c.Dt_Of_Join from emp_mst c  
                    join emp_mon_day d 
                    on c.emp_card_no=d.emp_mkey 
                    WHERE Dt_Of_Join =  CAST(FLOOR(CAST( DATEADD(month, -6, GETDATE()) AS FLOAT ))AS DATETIME)                  
            OPEN daily_Allocate   
            FETCH NEXT FROM daily_Allocate INTO
            @emp_card_no, @emp_name, @Dt_Of_Join                
            WHILE @@FETCH_STATUS = 0   
            BEGIN                                           
                    select  @Total_days = Sum(total_day),@Days_worked = Sum(days_worked)
                    from emp_mon_day a      
                    where  a.emp_mkey = 2519
                    group by emp_mkey                               
                        PRINT 'Employee Card no = ' + cast(@emp_card_no as char)
                        PRINT 'Total days = ' + cast(@Total_days as char)
                        PRINT 'Days Worked = ' +    cast(@Days_worked as char)                  
                set @Final_PaidDayLop = 0;
                set @TotalRecord = 0;       

                 Select @Final_PaidDayLop =  
                    isnull(sum(days),0)
                    from  P_Emp_Del_App_Hdr c join P_Emp_Del_App_trl d on c.mkey=d.mkey       
                    where c.delete_flag='N' and app_flag='Y' and c.year = @actualYear
                   and c.emp_mkey = @emp_card_no              

            Select @TotalRecord =  ((1.75 * 6) / @Total_days) * (@Days_worked + @Final_PaidDayLop) 
                from emp_mon_day a where  a.emp_mkey = @emp_card_no group by a.emp_mkey                         

        PRINT 'Final Paid LOP '  + cast(coalesce(@Final_PaidDayLop,0) as char)  
        PRINT 'Total Record ' + cast(coalesce(@TotalRecord,0) as char)                  

                    INSERT INTO @Results
                            ( Emp_card_no ,
                              Total_days ,
                              Days_worked ,
                              Final_PaidDayLop
                            )
                    VALUES  ( @emp_card_no , -- Emp_card_no - numeric
                              @Total_days , -- Total_days - numeric
                              @Days_worked , -- Days_worked - numeric
                              @Final_PaidDayLop  -- Final_PaidDayLop - numeric
                            )
                  FETCH NEXT FROM daily_Allocate INTO 
                  @emp_card_no, @emp_name, @Dt_Of_Join 
            END   
        CLOSE daily_Allocate   
        DEALLOCATE daily_Allocate

    SELECT 'Yes I am in the Current process', *
    FROM @Results

END     
END

我还建议整理变量命名的格式和一致性,以便更容易手动解析。一些错误处理以确保您的光标也始终关闭会很有用。

还建议将光标声明为 FAST_FORWARD、READ_ONLY:

What is the advantage of using FAST_FORWARD for defining a cursor?

【讨论】:

从表名中选择 *? 我像这样跑Select * from Results,但给出错误Invalid object name 'Results'. @coder 希望此链接有助于声明表变量值范围dba.stackexchange.com/questions/69217/… @KrunalMevada:你能更新一下,让我知道我的情况吗,因为我也对那个链接感到困惑 没有表'Results' - 它被称为@Results,它位于sproc 的范围内,而不是在它之外。如果您只是执行存储过程,您应该会看到结果,或者像以前一样将它们插入 #Temp 并从中选择。【参考方案3】:

不是打印值,而是将其存储在局部变量中(或插入表变量中)并从存储过程中返回,然后它将起作用

例如:-

BEGIN
....
DECLARE @v_str AS NVARCHAR(500)
SET @v_str = ''
...
SELECT @v_str = @v_str+'Yes I am in the Current process'
...
SELECT @v_str = @v_str+'Total Records'
.
.
SELECT @v_str AS result
END

【讨论】:

【参考方案4】:

试试这个而不是光标:

    declare @dt_of_join date

    set @dt_of_join = DATEADD(month, -6, GETDATE())

    Select 
      c.emp_card_no, c.emp_name,
      (1.75 * 6) / NullIf(d.Total_days, 0)) * (IsNull(d.Days_worked, 0) + IsNull(p.Final_PaidDayLop, 0)) as TotalRecord
    from dbo.emp_mst c  
    outer apply
    (
      select 
        sum(d.total_day) as total_days
        sum(d.days_worker) as days_worker
      from dbo.emp_mon_day d
      WHERE d.emp_mkey = c.emp_card_no
      GROUP BY d.emp_mkey
    ) d
    outer apply
    (
      select sum(cc.days) as Final_PaidDayLop
      from  P_Emp_Del_App_Hdr cc
      inner join P_Emp_Del_App_trl dd on cc.mkey=d.mkey
      where cc.delete_flag='N' and dd.app_flag='Y' 
        and cc.year = c.Dt_Of_Join
        and cc.emp_mkey = c.emp_card_no
    ) p
    where c.Dt_Of_Join = @dt_of_join

不确定是否猜对了所有内容(包括别名)。

如果您愿意,可以使用insert exec 或任何其他插入临时表的方式。

【讨论】:

以上是关于将存储过程数据插入临时表不起作用的主要内容,如果未能解决你的问题,请参考以下文章

插入带有参数MYSQL的存储过程不起作用

插入选择存储过程不起作用插入NULL

从后面的 C# 代码调用存储过程时插入语句不起作用

MYSQL 从存储过程中的临时表中选择 JOIN 不起作用

Cassandra中的数据建模简单表不起作用

使用存储过程执行时,executeUpdate() 不起作用