SQL Server +将select语句中的值插入表中

时间:2013-03-04 17:49:20

标签: sql

是否可以这样做:

SELECT UserName FROM payroll p
INNER JOIN aspnet_Users u
ON (p.staffId= u.UserId)
WHERE jobId = '1011'

例如,如果上面的select返回说3个结果:john001,mary002,peter003

如何使用它将单个结果插入到我的表(通知)列中?在这种情况下,只有[Recipient]列具有不同的值,并且将从上面的Select语句返回结果。

INSERT INTO [Notification]
(
[Recipient], 
[Message],
[Type],
[DateCreated]
)
VALUES
(
-- The results from the select statement
'Testing Message'
'Type1,
GETUTCDATE()
)

所以最终我应该在我的通知表中包含这些列:

john001, Testing Message, Type1, 10/10/1945
mary002, Testing Message, Type1, 10/10/1945
peter003, Testing Message, Type1, 10/10/1945

提前致谢。

3 个答案:

答案 0 :(得分:2)

您需要使用INSERT INTO..SELECT..FROM查询:

INSERT INTO [Notification]
(
    [Recipient], 
    [Message],
    [Type],
    [DateCreated]
)
SELECT UserName, 'Testing Message', 'Type1', GETUTCDATE()
FROM payroll p
INNER JOIN aspnet_Users u
    ON (p.staffId= u.UserId)
WHERE jobId = '1011'

参考资料:

答案 1 :(得分:1)

你可以做到

INSERT INTO [Notification]
(
[Recipient], 
[Message],
[Type],
[DateCreated]
)
SELECT UserName, 
'Testing Message' 
'Type1,
GETUTCDATE()
FROM payroll p
INNER JOIN aspnet_Users u
ON (p.staffId= u.UserId)
WHERE jobId = '1011'
  

您可以使用INSERT和SELECT语句以下列方式向表中添加行:

     

使用INSERT语句直接指定值或从子查询指定值。

     

将SELECT语句与INTO子句一起使用。

http://msdn.microsoft.com/en-us/library/ms188263(v=sql.105).aspx

补充参考:

http://blog.sqlauthority.com/2007/08/15/sql-server-insert-data-from-one-table-to-another-table-insert-into-select-select-into-table/

答案 2 :(得分:1)

INSERT INTO Notification
(
Recipient, 
Message,
Type,
DateCreated
)
SELECT UserName, 'Testing Messag', 'Type1', GETUTCDATE()
 FROM payroll p
 JOIN aspnet_Users u
  ON (p.staffId= u.UserId)
Where jobId = '1011'