我想從table1中選擇最後一條記錄並插入到另一個表中。這裏是我的查詢。如何從表中選擇記錄並插入到另一個表中?
Insert into table2 values(select top 1 col1,col2 from table1 order by id desc).
我知道爲表中添加值需要在cotation.But在哪裏添加?
我想從table1中選擇最後一條記錄並插入到另一個表中。這裏是我的查詢。如何從表中選擇記錄並插入到另一個表中?
Insert into table2 values(select top 1 col1,col2 from table1 order by id desc).
我知道爲表中添加值需要在cotation.But在哪裏添加?
您可以選擇文字在其他列填補table1
不能提供,這樣的事情:
insert into table2 (col_a, col_b, col_c, col_d)
select top 1 col1, col2, 'foo', 'bar'
from table1
order by id desc
任何列不列列表名稱將得到默認值,或null
如果沒有定義默認值。
所選列的數量和類型必須與插入列列表中列的數量和類型相匹配。
在SQL中,基本上有兩種將數據插入表的方法:一種是一次插入一行,另一種是一次插入多行。讓我們來看看他們每個人單獨:
INSERT INTO table_name (column1, column2, ...)
VALUES ('value1', 'value2', ...)
第二種INSERT INTO允許我們多行插入表中。與前面的例子不同,我們通過指定所有列的值來插入單行,現在我們使用SELECT語句指定要插入表中的數據。如果您在考慮這是否意味着您正在使用來自其他表格的信息,那麼您是正確的。語法如下:
INSERT INTO table1 (column1, column2, ...)
SELECT t2.column3, t2.column4, ...
FROM table2 t2
所以,在你的情況下,你可以做這樣的:
Insert into table2
select top 1 t1.col1,t1.col2 from table1 t1 order by id desc
或者你可以用你的語法如下:
declare @col1 type_of_col1, @col2 type_of_col2
select top 1 @col1 = t1.col1, @col2 = t1.col2 from table1 t1 order by id desc
Insert into table2 values(@col1, @col2)
Offcourse,這一切都假定列數據類型匹配。
這意味着'col1'和'col2'列是兩個表之間的相同名稱。情況可能並非如此。 – fge 2011-12-19 11:00:16
@fge offcourse,我假設.. – 2011-12-19 11:02:11
字符文字需要用單引號引起來,而不是雙引號:'VALUES('value1',...)' – 2011-12-19 11:02:42
+1感謝您保持簡單的答案! – 2011-12-19 11:22:01