【问题标题】:How to select multiple row values in to a variable in SQL Server 2005?如何在 SQL Server 2005 中的变量中选择多个行值?
【发布时间】:2019-04-30 14:36:53
【问题描述】:

我写了一个定义变量的脚本。

其中一个变量是这样定义的。

SET @Yesterday = (SELECT SUM (ri.Sales_Quantity) 
                  FROM ReportTransactions AS RT     
                  LEFT JOIN ReportItems AS ri ON rt.Report_Transaction_ID = ri.Report_Transaction_ID    
                  LEFT JOIN MMGroups AS mmg ON ri.MMGroup2_ID = MMG.ID  
                  LEFT JOIN Locations AS L ON L.Location_ID = RT.Store_ID 
                  WHERE rt.Transaction_Date > DATEADD(DAY, -1, GETDATE()) 
                    AND (NULL IS NULL OR rt.Store_ID = NULL)   
                    AND (rt.Training_Mode IS NULL OR rt.Training_Mode = 0)   
                    AND ri.Item_Voided = 0   
                    AND ri.Void_Type = 0
                    AND rt.Transaction_Type IN (0, 1, 2, 3, 4, 5, 6)   
                    AND ri.Item_Type IN (1, 2, 3, 4, 6, 7, 54, 55, 81, 84, 11, 12, 13, 22, 25, 27, 82) 
                  GROUP BY  
                      RT.Store_ID);

然而,这会返回多个值,因此无法定义变量并引发错误。

我的报告需要所有这些行,那么如何定义它们并检索它们,最佳做法是什么?

【问题讨论】:

  • 将它们存储在临时表中,而不是变量中。

标签: sql sql-server-2005


【解决方案1】:

您需要表格 temporarybase 因为您需要多行或多列:

SELECT RT.Store_ID, SUM (ri.Sales_Quantity) AS Sum_Qty INTO #table
FROM ReportTransactions AS RT LEFT JOIN 
     ReportItems AS ri 
     ON rt.Report_Transaction_ID = ri.Report_Transaction_ID LEFT JOIN 
     MMGroups AS mmg 
     ON ri.MMGroup2_ID = MMG.ID LEFT JOIN 
     Locations AS L 
     ON L.Location_ID = RT.Store_ID 
WHERE . . .     
GROUP BY RT.Store_ID;

然而,基表需要INSERT INTO 语句和SELECT 语句:

INSERT INTO table (col1, col2)
     SELECT . . . ;

【讨论】:

    【解决方案2】:

    也许你可以试试表变量。

    DECLARE @Yesterday  Table
    (
    Sum_Qty  int
    )
    insert into @Yesterday
    SELECT SUM (ri.Sales_Quantity) 
                      FROM ReportTransactions AS RT     
                      LEFT JOIN ReportItems AS ri ON rt.Report_Transaction_ID = ri.Report_Transaction_ID    
                      LEFT JOIN MMGroups AS mmg ON ri.MMGroup2_ID = MMG.ID  
                      LEFT JOIN Locations AS L ON L.Location_ID = RT.Store_ID 
                      WHERE rt.Transaction_Date > DATEADD(DAY, -1, GETDATE()) 
                        AND (NULL IS NULL OR rt.Store_ID = NULL)   
                        AND (rt.Training_Mode IS NULL OR rt.Training_Mode = 0)   
                        AND ri.Item_Voided = 0   
                        AND ri.Void_Type = 0
                        AND rt.Transaction_Type IN (0, 1, 2, 3, 4, 5, 6)   
                        AND ri.Item_Type IN (1, 2, 3, 4, 6, 7, 54, 55, 81, 84, 11, 12, 13, 22, 25, 27, 82) 
                      GROUP BY  
                          RT.Store_ID
    

    【讨论】:

      猜你喜欢
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      相关资源
      最近更新 更多