在SQL中循环创建表

时间:2017-07-11 13:38:45

标签: sql sql-server

我正在尝试创建一个如下所示的表格,我想知道是否有一种快速的方法来创建它而不是使用大量的联合。

 | Week_No | Day_Of_Week |
 |    1    |       1     |
 |    1    |       2     |
 |    1    |       3     |
 |    1    |       4     |
 |    1    |       5     |
 |    2    |       1     |
 |    2    |       2     |
 |    2    |       3     |
 |    2    |       4     |
 |    2    |       5     |

我需要创建它以使week_no上升到53,每周必须有1-5。

我使用的是Sql Server。

此致

尼尔

6 个答案:

答案 0 :(得分:2)

  <uses-permission android:name="android.permission.INTERNET" />

答案 1 :(得分:2)

应尽可能避免循环。如果您没有数字/计数表,则可以使用临时计数表。

;with cte0(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
      cteN(N) As (Select Row_Number() over (Order By (Select NULL)) From cte0 N1, cte0 N2)
Select Week_No=A.N
      ,Day_Of_Week = B.N
 From cteN A
 Cross Apply cteN B
 Where A.N<=53 and B.N<=5

答案 2 :(得分:1)

您必须使用CREATE TABLE语法,但您可以尝试以下

create table tbl1( Week_No int, Day_Of_Week int);
insert into tbl1( Week_No , Day_Of_Week ) values (1,1),(1,2),(1,3),(1,4),(1,5),(1,6),....

答案 3 :(得分:1)

首先,创建两个表变量 - 并在其中存储1-5和1-53(几天和几周)。然后笛卡儿加入这两个,你就完成了!将最后一个SELECT语句更改为目标表中的插入,您就完成了。

DECLARE @WeekNumbers TABLE (WeekNo int)
DECLARE @DaysOfWeek TABLE (DayOfWeek int)

DECLARE @Count INT = 1

WHILE @Count <= 53
    BEGIN
        INSERT INTO @WeekNumbers
        VALUES
        (@Count)

        SET @Count = @Count + 1
    END

SET @Count = 1

WHILE @Count <= 5
    BEGIN
        INSERT INTO @DaysOfWeek
        VALUES
        (@Count)

        SET @Count = @Count + 1
    END

SELECT * 
FROM @WeekNumbers, @DaysOfWeek

答案 4 :(得分:1)

递归公用表表达式:

from bs4 import BeautifulSoup as soup
from urllib.request import urlopen

my_url = urlopen("http://edition.cnn.com/?refresh=1")

sauce = my_url.read()

soup = soup(sauce,"lxml")

my_div = soup.find("div",{"class":"pg-no-rail"})

my_sections = my_div.findAll("section")

for section in my_sections:
    print(section)

my_url.close()

答案 5 :(得分:1)

declare @days_of_week int
declare @weekNbr int

set @weekNbr=1

while @weekNbr<=53

begin

set @days_of_week=1

while @days_of_week<=5
begin

 select @weekNbr,@days_of_week

set @days_of_week=@days_of_week+1
end
set @weekNbr=@weekNbr+1
end