将行数据从一个表安全地插入到另一个表中 - SQL
我需要使用脚本将存储在一个表中的一些数据移动到另一个表中,同时考虑目标表中可能已经存在的现有记录以及可能存在的任何关系。
我很想知道执行此操作的最佳方法,该方法对性能的影响相对较小,并且在必要时可以逆转。
一开始我将仅移动一条记录以确保流程顺利运行,但随后它将负责移动大约 1650 行。
最好的方法是什么或者有更好的选择吗?
编辑:
我之前使用 MERGE 的建议将不起作用,因为我将在 SQL Server 2005 环境下操作,而不是前面提到的 2008 环境。
I need to move some data stored in one table to another using a script, taking into account existing records that may already be in the destination table as well as any relationships that may exist.
I am curious to know the best method of doing this that has a relatively low impact on performance and can be reversed if necessary.
At first I will be moving only one record to ensure the process runs smoothly but then it will be responsible for moving around 1650 rows.
What would be the best approach to take or is there a better alternative?
Edit:
My previous suggestion of using MERGE will not work as I will be operating under the SQL Server 2005 environment, not 2008 like previously mentioned.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该问题没有提供任何详细信息,因此我无法提供任何实际的代码,仅提供以下攻击计划:
第1步编写一个仅选择行的查询你需要复制。您需要
JOIN
和/或过滤(WHERE
)此数据,以仅包含目标表中尚不存在的行。使列列表在列顺序和数据类型方面与目标表的列完全相同。第 2 步 通过在选择之前添加
INSERT YourDestinationTable (col1, col2, col3..)
将该 SELECT 语句转换为 INSERT。第 3 步如果您只想尝试单行,请将
TOP 1
添加到新INSERET - SELECT 命令
的选择部分,您可以在有/没有TOP
的情况下根据需要多次重新运行此命令,因为它应该消除通过JOIN
和WHERE
条件添加的任何行在SELECT
最后,您将得到如下所示的内容:
我正在阅读问题,因为仅将源表中缺少的行插入到目标表中。如果还需要迁移更改,那么在执行上述步骤之前,您将需要对连接源表的目标表执行
UPDATE
。如果没有实际表、列等的更多细节,这很难解释。the question does not provide any details, so I can't provide any actual real code, just this plan of attack:
step 1 write a query that will SELECT only the rows you need to copy. You will need to
JOIN
and/or filter (WHERE
) this data to only include the rows that don't already exist in the destination table. Make the column list be the exact same as the destination table's columns, in column order and data type.step 2 turn that SELECT statement into an INSERT by adding
INSERT YourDestinationTable (col1, col2, col3..)
before the select.step 3 if you only want to try a single row, add a
TOP 1
to the select part of the newINSERET - SELECT command
, you can rerun this command as many times as necessary with/without aTOP
because it should eliminate any rows you add by theJOIN
s andWHERE
conditions in theSELECT
in the end, you'll have something that looks like:
I'm reading the question as only inserting missing rows from a source table to a destination table. If changes need to be migrated as well then prior to the above steps you will need to do an
UPDATE
of the destination table joining in the source table. This is hard to explain without more specifics of the actual tables, columns, etc.是的,如果您运行的是 SQL Server 2008,则 MERGE 语句非常适合批量导入。
Yes, the MERGE statement is ideal for bulk imports if you are running SQL Server 2008.