Sql 如何在insert into子句中从表中插入非顺序Id

Sql 如何在insert into子句中从表中插入非顺序Id,sql,sql-server,Sql,Sql Server,我需要在表2中插入表1的ID。问题在于表1中的顺序行没有顺序Id(有人删除了一些行,因此顺序行没有顺序Id) 从表1中选择*将导致: 表1 Id Value1 ------------ 2 X 4 Y 10 Z 12 XYZ 14 ZD 121 XD 122 ZS ------------ 表2的预期结果为: Id Value1 Value2 Date ----------------

我需要在表2中插入表1的ID。问题在于表1中的顺序行没有顺序Id(有人删除了一些行,因此顺序行没有顺序Id)

从表1中选择*将导致:

表1

Id    Value1
------------
2       X
4       Y
10      Z
12      XYZ
14      ZD
121     XD
122     ZS
------------
表2的预期结果为:

   Id    Value1   Value2      Date
    -----------------------------------
    1       67       2       2018-05-15
    2       67       4       2018-05-15
    3       67      10       2018-05-15
    4       67      12       2018-05-15
    5       67      14       2018-05-15
    6       67      121      2018-05-15
    7       67      122      2018-05-15
    ------------------------------------
在表2中插入值的代码。我只需要表1就可以复制正确的Id

declare @value int
set @value=(select count(*) from table1) 
while @value>0

            begin
                insert into (table2)
                values ('67',@HOW_TO_RETRIEVE THE CORRECT ID from TABLE 1?,getdate())
                set @value=@value-1

            end

当然,对于@value,它将不起作用,我尝试在values中使用select子句,但没有效果。谢谢

您不想对这种类型的东西使用循环。您可以很容易地在insert中使用select语句。像这样的工作对你来说。这是假设表2中的Id是一个标识。如果没有,我们可以利用ROW_NUMBER()生成顺序值

insert table2
(
    Value1
    , Value2
    , [Date]
)
select '67'
    , Id
    , getdate()
from Table1

您不希望对这种类型的事情使用循环。您可以很容易地在insert中使用select语句。像这样的工作对你来说。这是假设表2中的Id是一个标识。如果没有,我们可以利用ROW_NUMBER()生成顺序值

insert table2
(
    Value1
    , Value2
    , [Date]
)
select '67'
    , Id
    , getdate()
from Table1
像这样

alter table2 add id bigint identity(1,1)
;
insert table2 (Value1, Value2, Date)
select '67', ID ,getdate()
from TABLE1
;
像这样

alter table2 add id bigint identity(1,1)
;
insert table2 (Value1, Value2, Date)
select '67', ID ,getdate()
from TABLE1
;

只需在表2中创建标识列,它将以序号插入行。只需在表2中创建标识列,它将以序号插入行