[英]T-SQL query to select from one table and insert into another
Please read the question before marking this as a duplicate. 在将此问题标记为重复之前,请先阅读问题。
I am trying to insert a row into a table with 5 columns. 我试图将行插入到具有5列的表中。 I want 3 of those columns to come from another table, which I will read using a select query. 我希望其中三列来自另一个表,我将使用选择查询来读取该表。
INSERT INTO tbl.Log (
LogDate,
Object,
Count,
Creator,
LastUpdate)
SELECT TOP 1
GETUTCDATE(),
Object,
Count, -- I need to +1 to this
'John Smith',
LastUpdate
FROM tbl.Objects
WHERE ObjectID = '123'
ORDER BY LastUpdate DESC
I can see what I am doing wrong here: 我可以在这里看到我做错了什么:
GETUTCDATE()
should not go in the SELECT because it is not a column name. GETUTCDATE()
不应进入SELECT,因为它不是列名。 Where does it go instead? 它去哪儿了? 'John Smith'
as creator 作为创作者的'John Smith'
也是如此 I could do this manually by performing two separate queries and parsing the data from the SELECT
into the INSERT
query, but I am trying to improve my SQL. 我可以通过执行两个单独的查询并将SELECT
的数据解析为INSERT
查询来手动完成此操作,但是我正在尝试改进SQL。
You can select values that are not a part of your table and do arithmetic on columns during insert
. 您可以选择不属于表的值,并在insert
过程中对列进行算术运算。
INSERT INTO tbl.Log (
LogDate,
Object,
Count,
Creator,
LastUpdate)
SELECT TOP 1
GETUTCDATE(),
Object,
Count+1
'John Smith',
LastUpdate
FROM tbl.Objects
WHERE ObjectID = '123'
ORDER BY LastUpdate DESC
Understand that the idea of doing the insert
with two separate queries would result in 2 rows. 了解使用两个单独的查询进行insert
的想法将导致两行。
There is nothing wrong with selecting values that doesn't exist on the table, every RDBMS accepts it. 选择表中不存在的值没有错,每个RDBMS都接受它。
Also, what do you mean by count+1 ? 另外,count + 1是什么意思? The count that is inside the log table? 日志表中的计数是多少? If so: 如果是这样的话:
INSERT INTO tbl.Log (
LogDate,
Object,
Count,
Creator,
LastUpdate)
SELECT TOP 1
GETUTCDATE(),
Object,
(SELECT MAX(Count) FROM tbl.log),
'John Smith',
LastUpdate
FROM tbl.Objects
WHERE ObjectID = '123'
ORDER BY LastUpdate DESC
If you meant the count that on the Objects
table, that replace the sub select with count+1
, but that just seems like you could have done it your self. 如果要表示Objects
表中的计数,则用count+1
替换子选择,但这似乎可以自己完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.