从上次插入的行中获取数据

时间:2011-12-15 16:32:22

标签: sql sql-server select insert

我试图找出如何从我刚刚使用的INSERT语句中获取firstname和lastname。它创建了一行,我想在下一个插入语句中使用First Name和Last Name,我将如何进行此操作?

Declare @idnt int

INSERT INTO dbo.Contacts (ContactFirstName,ContactLastName,ContactCompany) VALUES ('Richard','Burns',NULL);

SELECT @idnt = SCOPE_IDENTITY()

INSERT INTO dbo.Activity (ContactID, ActivityDate, ActivityName, ActivityNote, ActivityOwner)
VALUES (@idnt, '12/13/2011 10:55AM', 'Contact ' + @fname + " " + @lname + ", was automatically added by the system', 'Contact was automatically added by this system', 'System')

3 个答案:

答案 0 :(得分:4)

使用output

INSERT INTO dbo.Activity (
    ContactID, 
    ActivityDate, 
    ActivityName, 
    ActivityNote, 
    ActivityOwner
)
SELECT 
    ContactID, 
    GETDATE(), 
    'Contact ' + ContactFirstName + ' ' + ContactLastName, 
    'Contact was added by the system.', 
    'System'
FROM (
    INSERT INTO dbo.Contacts (ContactFirstName,ContactLastName,ContactCompany) 
    OUTPUT inserted.ContactID, inserted.ContactFirstName, inserted.ContactLastName
    VALUES ('Richard','Burns',NULL)
) x

有关outputsee here

的魔力的更多信息

您还可以使用表格上的触发器使其自动化,而不必每次都手动插入。它也使用inserted / deleted表。

你会这样做:

CREATE TRIGGER Contact_LogActivity ON dbo.Contacts FOR INSERT AS
INSERT INTO dbo.Activity (
    ContactID, 
    ActivityDate, 
    ActivityName, 
    ActivityNote, 
    ActivityOwner
)
SELECT
    ContactID,
    GETDATE(), 
    'Contact ' + ContactFirstName + ' ' + ContactLastName, 
    'Contact was added by the system.', 
    'System'
FROM
    Inserted

现在,只要有任何行插入到Contacts中,它就会将其记录到Activity中。有关触发器的更多信息,请参阅here

答案 1 :(得分:0)

使用SCOPE_IDENTITY()抓住的身份,查询表格并将ContactFirstNameContactLastName分别抓取到声明的变量:@fname@lname

...
SELECT @idnt = SCOPE_IDENTITY()

SELECT
    @fname = ContactFirstName
  , @lname = ContactLastName
FROM dbo.Contacts 
WHERE YOUR_IDENTITY_COLUMN_HERE = @idnt

INSERT INTO dbo.Activity ...

YOUR_IDENTITY_COLUMN_HERE替换为您从中获取SCOPE_IDENTITY()的标识列的名称并测试..

答案 2 :(得分:0)

我认为您正在寻找带有select语句的插入。试试这个:

    INSERT INTO dbo.Activity (ContactID, ActivityDate, ActivityName, ActivityNote, ActivityOwner)
    SELECT @idnt, '12/13/2011 10:55AM', 'Contact ' + ContactFirstName + ' ' + ContactLastName + ', was automatically added by the system', 'Contact was automatically added by this system', 'System'
    FROM Contacts
    WHERE ContactId = @idnt