Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 使用基于集合的查询代替游标_Sql_Sql Server_Cursor - Fatal编程技术网

Sql 使用基于集合的查询代替游标

Sql 使用基于集合的查询代替游标,sql,sql-server,cursor,Sql,Sql Server,Cursor,需要根据多组科目作为条件运行查询。试图避免游标/while循环场景。@MasterGroup变量是游标迭代器,直接从Group table派生而来,Group table是一对多的变量,其帐户来自Group table,然后在WHERE子句的子查询中使用。最终结果将填充到带有@MasterGroup整数的新表中。有没有办法避免在这里使用游标/循环?非常感谢 Insert Into SAGTranTmp SELECT @MasterGroup, C1.Cust_T

需要根据多组科目作为条件运行查询。试图避免游标/while循环场景。@MasterGroup变量是游标迭代器,直接从Group table派生而来,Group table是一对多的变量,其帐户来自Group table,然后在WHERE子句的子查询中使用。最终结果将填充到带有@MasterGroup整数的新表中。有没有办法避免在这里使用游标/循环?非常感谢

Insert Into SAGTranTmp
SELECT 
        @MasterGroup,
        C1.Cust_Type,
        T1.Exclude,
        T1.Acct_No,
        SUM(Tran_Amt) AS [Amount]
FROM dbo.Trans AS [T1]
     JOIN dbo.Customers AS C1 ON T1.Acct_No = C1.Acct_No
WHERE C1.Acct_No IN (
        SELECT AcctNo 
        FROM SignAcc_Group
        WHERE MasterGroup = @MasterGroup)

我可能过于简化了,如果我这样做了,请道歉,但请尝试一下,希望它能有所帮助


假设主组为表主组int。 你可以试试这个:

;WITH 
temp AS (SELECT DISTINCT
    mg.MasterGroup,
    T1.Acct_No
 FROM dbo.Trans AS [T1]
       Inner JOIN dbo.Customers AS C1 ON T1.Acct_No = C1.Acct_No
       inner join SignAcc_Group as sg ON C1.Acct_No = sg.AcctNo 
       inner join #MasterGroup mg ON sg.MasterGroup  = mg.MasterGroup        
         )
 Insert Into SAGTranTmp
 SELECT 
    t.MasterGroup,
    C1.Cust_Type,
    T1.Exclude,
    T1.Acct_No,
    SUM(Tran_Amt) AS [Amount]
 FROM temp t 
 INNER JOIN dbo.Trans AS [T1] ON T1.Acct_No = t.Acct_No 
 INNER JOIN dbo.Customers AS C1 ON T1.Acct_No = C1.Acct_No
 GROUP BY t.MasterGroup,
       C1.Cust_Type,
       T1.Exclude,
       T1.Acct_No

请编辑您的问题以包括示例数据和所需结果谢谢-现在在带有56MM表格的tran表格上运行此功能。单独的实例正在运行游标版本。会让你知道结果。干杯
;WITH 
temp AS (SELECT DISTINCT
    mg.MasterGroup,
    T1.Acct_No
 FROM dbo.Trans AS [T1]
       Inner JOIN dbo.Customers AS C1 ON T1.Acct_No = C1.Acct_No
       inner join SignAcc_Group as sg ON C1.Acct_No = sg.AcctNo 
       inner join #MasterGroup mg ON sg.MasterGroup  = mg.MasterGroup        
         )
 Insert Into SAGTranTmp
 SELECT 
    t.MasterGroup,
    C1.Cust_Type,
    T1.Exclude,
    T1.Acct_No,
    SUM(Tran_Amt) AS [Amount]
 FROM temp t 
 INNER JOIN dbo.Trans AS [T1] ON T1.Acct_No = t.Acct_No 
 INNER JOIN dbo.Customers AS C1 ON T1.Acct_No = C1.Acct_No
 GROUP BY t.MasterGroup,
       C1.Cust_Type,
       T1.Exclude,
       T1.Acct_No