繁体   English   中英

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

[英]SQL Server + Inserting values from a select statement into a table

是否有可能做到这一点:

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()
)

所以最终我应该在我的Notification表中有这些列:

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

提前致谢。

您将需要使用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'

参考资料:

你可以做到

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/

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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM