1

是否有可能做到这一点:

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

例如,如果上面的选择返回 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

提前致谢。

4

3 回答 3

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'

参考资料:

于 2013-03-04T17:51:59.570 回答
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 语句直接或从子查询中指定值。

使用带有 INTO 子句的 SELECT 语句。

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/

于 2013-03-04T17:52:39.767 回答
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'
于 2013-03-04T17:55:47.930 回答