[英]Looping through rows of a table using each row as Insert Into - SQL
[英]Looping through specific values on a table and insert new rows
我有下表:
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
並且需要某種循環。
那可行嗎?
使用CTE代表帳戶和日期序列。 對於帳戶ID值,我們可以使用遞歸CTE。 下面我隨意生成1
到100
值,盡管這種方法應該適用於任何連續范圍。 對於年/月組合,由於只有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
)
嘗試這個。 這與已經存在的答案非常相似,但更為緊湊:
;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
如果您有一個accountId存儲在一個表中,並且您想要為Month1的每個帳戶ID插入10行(從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
如果需要不同的值,請更改ween子句
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.