循环遍历表上的特定值并插入新行

时间:2017-12-14 08:34:30

标签: sql sql-server

我有下表:

ID, UserID, CompanyID, AccountID, Year1, Month1

我需要为每个AccountID插入10行,有没有办法循环遍历所有AccountID并为每一个插入以下值?

INSERT INTO Perms (UserID, CompanyID, AccountID, Year1, Month1)
VALUES
    (175, 74,x,2017,3),
    (175, 74,x,2017,4),
    (175, 74,x,2017,5),
    (175, 74,x,2017,6),
    (175, 74,x,2017,7),
    (175, 74,x,2017,8),
    (175, 74,x,2017,9),
    (175, 74,x,2017,10),
    (175, 74,x,2017,11),
    (175, 74,x,2017,12)

我有大约100 AccountID s,我需要某种循环。

可行吗?

3 个答案:

答案 0 :(得分:2)

使用CTE表示帐户和日期序列。在帐户ID值的情况下,我们可以使用递归CTE。我在下面任意生成从1100的值,但这种方法适用于任何连续范围。对于年/月组合,因为只有10个,我们可以简单地在CTE中对它们进行硬编码。然后,将INSERT INTO ... SELECT与两个CTE的交叉连接一起使用。

WITH accounts AS ( 
    SELECT 1 AS account
    UNION ALL 
    SELECT account + 1 
    FROM accounts 
    WHERE account + 1 <= 100
),
cte AS (
    SELECT 2017 AS year, 3 AS month UNION ALL
    SELECT 2017, 4 UNION ALL
    SELECT 2017, 5 UNION ALL
    SELECT 2017, 6 UNION ALL
    SELECT 2017, 7 UNION ALL
    SELECT 2017, 8 UNION ALL
    SELECT 2017, 9 UNION ALL
    SELECT 2017, 10 UNION ALL
    SELECT 2017, 11 UNION ALL
    SELECT 2017, 12
)
INSERT INTO Perms (UserID, CompanyID, AccountID, Year1, Month1)
SELECT 175, 74, account, year, month
FROM accounts
CROSS JOIN cte;
OPTION (MAXRECURSION 255);

修改

如果您的帐户ID不是连续的,那么继续这个答案,您可以手动将它们列在CTE中,例如

WITH accounts AS ( 
    SELECT 71 AS account UNION ALL
    SELECT 74 UNION ALL
    SELECT 78 UNION ALL
    SELECT 112 UNION ALL
    SELECT 119
    -- and others
)

答案 1 :(得分:1)

试试这个。这与已经存在的答案非常类似,但更紧凑:

;with cte as (
  select 175 [UserID], 74 [CompanyID], 2017 [Year1], 3 [Month1]
  union all
  select 175 [UserID], 74 [CompanyID], 2017 [Year1], [Month1] + 1 from cte
  where [Month1] < 12
)
select A.[UserID], A.[CompanyID], B.[AccountID], A.[Year1], A.[Month1] from cte A cross join TABLE_NAME B

答案 2 :(得分:0)

如果您将accountId存储在一个表格中,您想要的是为每个帐户ID插入10行,其中Month1从3到12,请尝试使用

WITH CTE
AS
(
    SELECT
        Month2 = 1

    UNION ALL

    SELECT
        Month2+1
        FROM CTE
            WHERE Month2 <12
)
INSERT INTO Perms (UserID, CompanyID, AccountID, Year1, Month1)
SELECT
    UserID = 175, 
    CompanyID ='X', 
    AccountID = YAT.AccountID, 
    Year1 = 2017, 
    Month1 = CTE.Month2
    FROM CTE
        INNER JOIN YourAccountTable YAT
            ON CTE.Month2 BETWEEN 3 AND 12

如果您想要不同的值

,请更改between子句