Sql 从同一个表上的select中插入,并将新旧标识值存储在单独的表中

Sql 从同一个表上的select中插入,并将新旧标识值存储在单独的表中,sql,sql-server,identity,Sql,Sql Server,Identity,临时表格: declare @Temp_Table table ( newSID int, oldSID int ) 数据库表:解决方案 Solutions: * 1 solution1 1

临时表格:

declare @Temp_Table table
                                   (
                                        newSID int,
                                        oldSID int
                                   )
数据库表:
解决方案

Solutions:

* 1   solution1  111
* 2   solution2  111
* 3   solution3  111
插入后

* 1   solution1  111
* 2   solution2  111
* 3   solution3  111
* 4   solution1  222
* 5   solution2  222
* 6   solution3  222
需要临时表

  oldsID  NewSID

* 1              4
* 2              5
* 3              6
此表具有
SID
(标识)、
SName
和cnumber

现在我想从
Solutions
表中选择一些行,并将它们的值插入到同一个表中

插入每一行时,我希望将旧标识值和新标识值存储在临时表中(
@Temp\u table


请帮我解决这个问题。

诀窍是使用
merge
而不是常规的
插入..选择
,因为使用
merge
可以在
输出
子句中同时使用源数据和目标数据

首先,创建并填充样本表(请在以后的问题中保存此步骤):

然后,声明映射表:

DECLARE @Temp_MasterSolutionsTable AS TABLE
(
    newSolutionID int,
    oldSolutionID int
)
接下来,复制所需的记录:

MERGE INTO Solutions USING
(
    SELECT SolutionID, SolutionName, ClientNumber
    FROM Solutions
    --WHERE CONDITION -- I'm guessing you will need a where clause here
) AS s ON 1 = 0 -- Always not matched
WHEN NOT MATCHED THEN
INSERT (SolutionName, ClientNumber)
VALUES (s.SolutionName, s.ClientNumber)
-- and here is where the magic happens
OUTPUT Inserted.SolutionID, s.SolutionID
INTO @Temp_MasterSolutionsTable (newSolutionID, oldSolutionID); 

Google
SQL输出子句
您的问题一点也不清楚!!请给我们您的选择查询,我们不知道我们应该在
newSolutionID
中放入什么,在
oldSolutionID
中放入什么!!newSolutionID是最近插入的标识值,oldSolutionID是选定的行标识值。例如:插入到解决方案(solutionname)从解决方案中选择solutionname。(在这里,我需要获取select语句标识值和新插入的标识值,并将它们存储到临时表中。。您尝试执行的操作的上下文丢失,因为您没有共享有关正在尝试的进程的足够信息。谢谢,它对我有效。。您能检查以下问题吗:
MERGE INTO Solutions USING
(
    SELECT SolutionID, SolutionName, ClientNumber
    FROM Solutions
    --WHERE CONDITION -- I'm guessing you will need a where clause here
) AS s ON 1 = 0 -- Always not matched
WHEN NOT MATCHED THEN
INSERT (SolutionName, ClientNumber)
VALUES (s.SolutionName, s.ClientNumber)
-- and here is where the magic happens
OUTPUT Inserted.SolutionID, s.SolutionID
INTO @Temp_MasterSolutionsTable (newSolutionID, oldSolutionID);