将行复制并粘贴到具有不同值的同一 SQL 表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9672508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy and Paste Rows into Same SQL Table with Different Values
提问by Dave Mackey
I wrote an application for resident housing at a college. In one of the tables (rooms) I have a list of all the rooms and their current/max occupancy. Now, I've added a new column called "semester" and set all of the existing rows to have a semester value of "fall." Now I want copy and paste all of these rows into the table but change the semester value to "spring." The result should be twice as many rows as I started with - half with fall in the semester value and half with fall. Wondering what the best way to accomplish this is?
我写了一份大学住宿申请。在其中一张桌子(房间)中,我列出了所有房间及其当前/最大入住人数。现在,我添加了一个名为“semester”的新列,并将所有现有行的学期值设置为“fall”。现在我想将所有这些行复制并粘贴到表中,但将学期值更改为“spring”。结果应该是我开始时行数的两倍 - 学期值下降一半,下降一半。想知道实现这一目标的最佳方法是什么?
回答by squillman
INSERT INTO rooms
(roomname, current_occupancy, max_occupancy, semester)
SELECT roomname, current_occupancy, max_occupancy,'spring'
FROM rooms
WHERE [semester]='fall'
(assuming names for your room and occupancy columns)
(假设您的房间和入住栏的名称)
回答by Joachim Isaksson
Use a temp table to make it simple no matter how many columns are involved;
无论涉及多少列,都使用临时表使其变得简单;
SELECT * INTO #ROOMS FROM ROOMS;
UPDATE #ROOMS SET SEMESTER='spring';
INSERT INTO ROOMS SELECT * FROM #ROOMS;
回答by Ta01
Insert Into Rooms
Select col1, col2, col3, 'Spring' as Semester -- select each column in order except 'Semester', pass it in literally as 'Spring'
From rooms where
Semester = 'Fall'
回答by The Muffin Man
Well if you're just trying to do this inside Sql Server Management Studio you could copy the table, run an Update command and set the semester to spring on the cloned table, then use the wizard to append the data from the cloned table to the existing table.
好吧,如果您只是想在 Sql Server Management Studio 中执行此操作,您可以复制表,运行更新命令并将学期设置为在克隆表上弹出,然后使用向导将克隆表中的数据附加到现有表。
If you know a programming language you could pull all of the data, modify the semester, then insert the data into the existing table.
如果您知道一种编程语言,您可以提取所有数据,修改学期,然后将数据插入现有表中。
Note: The other answers are a much better way of achieving this.
注意:其他答案是实现这一目标的更好方法。