SQL 脚本人口 table
SQL script population table
我有一个问题:如何在 table 中自动插入一些行?
我这样做了:
INSERT INTO ASSEMBLY (Machine_ID, Assembly_model, Assembly_text, Serial_number)
VALUES (1, '592-000', 'Model in text form', 148)
其中 Machine_ID
是主键。
如何在 table 中添加行,自动递增 Machine_ID
和 Serial_number
列?
我想在不手动更改数据的情况下添加 300 行;我正在使用 SQL Server Management Studio 来处理数据库。
您可以使用 row_number()
对大 table 生成一系列数字,然后在 insert ... select
语句中使用该信息:
with cte as (select row_number() over(order by (select null)) rn from bigtable)
insert into assembly (machine_id, assembly_model, assembly_text, serial_number)
select rn, '592-000', 'Model in text form', 147 + rn
from cte
where rn <= 300
您可以将 CTE 中的 bigtable
替换为至少有 300 行的任何现有 table(例如,您可以使用 sys.columns
)。
如果table中已有记录,则:
with cte as (select row_number() over(order by (select null)) rn from bigtable)
insert into assembly (machine_id, assembly_model, assembly_text, serial_number)
select a.max_machine_id + c.rn, '592-000', 'Model in text form', 147 + c.rn
from cte c
cross join (select max(machine_id) max_machine_id from assembly) a
where rn <= 300
这会将 300 条记录添加到 table,从最大可用的 machine_id
开始。另一方面,如果您想填充 table 直到 300 条记录,则只需更改 where
子句:
where c.rn + a.machine_id <= 300
我有一个问题:如何在 table 中自动插入一些行?
我这样做了:
INSERT INTO ASSEMBLY (Machine_ID, Assembly_model, Assembly_text, Serial_number)
VALUES (1, '592-000', 'Model in text form', 148)
其中 Machine_ID
是主键。
如何在 table 中添加行,自动递增 Machine_ID
和 Serial_number
列?
我想在不手动更改数据的情况下添加 300 行;我正在使用 SQL Server Management Studio 来处理数据库。
您可以使用 row_number()
对大 table 生成一系列数字,然后在 insert ... select
语句中使用该信息:
with cte as (select row_number() over(order by (select null)) rn from bigtable)
insert into assembly (machine_id, assembly_model, assembly_text, serial_number)
select rn, '592-000', 'Model in text form', 147 + rn
from cte
where rn <= 300
您可以将 CTE 中的 bigtable
替换为至少有 300 行的任何现有 table(例如,您可以使用 sys.columns
)。
如果table中已有记录,则:
with cte as (select row_number() over(order by (select null)) rn from bigtable)
insert into assembly (machine_id, assembly_model, assembly_text, serial_number)
select a.max_machine_id + c.rn, '592-000', 'Model in text form', 147 + c.rn
from cte c
cross join (select max(machine_id) max_machine_id from assembly) a
where rn <= 300
这会将 300 条记录添加到 table,从最大可用的 machine_id
开始。另一方面,如果您想填充 table 直到 300 条记录,则只需更改 where
子句:
where c.rn + a.machine_id <= 300