INSERT INTO存储过程的输出

时间:2013-04-22 12:25:14

标签: sql sql-server stored-procedures

我正在编写一个存储过程,我首先在表中插入一个新行。然后,另一个查询需要此查询生成的ID。是否可以使用OUTPUT访问prevoisly生成的ID?

这是我到目前为止所做的事情,而且几乎猜测它没有用到

ALTER PROCEDURE [dbo].[addApp]

      @Name varchar(50) 
    , @logoUrl varchar(150)
    , @siteUrl varchar(150)
    , @userId int
    , @canvasWidth int
    , @canvasHeight int

AS
DECLARE @tempId INT
SET @tempid = INSERT INTO AppInfo (name, logoUrl, userId) 
              OUTPUT inserted.id 
              VALUES(@Name, @logoUrl, @userId);
INSERT INTO CanvasApps (id, siteUrl, canvasWidth, canvasHeight)
OUTPUT inserted.id
VALUES(@tempid, @siteUrl, @logoUrl, @userId);

6 个答案:

答案 0 :(得分:5)

您甚至可以在单一声明中执行此操作:

ALTER PROCEDURE [dbo].[addApp] 

      @Name VARCHAR(50)
    , @logoUrl VARCHAR(150)
    , @siteUrl VARCHAR(150)
    , @userId INT
    , @canvasWidth INT
    , @canvasHeight INT

AS BEGIN

    INSERT INTO dbo.AppInfo (name, logoUrl, userId) 
    OUTPUT Inserted.ID, @siteUrl, @canvasWidth , @canvasHeight
       INTO dbo.CanvasApps (id, siteUrl, canvasWidth, canvasHeight)
    VALUES (@Name, @logoUrl, @userId)

END 

答案 1 :(得分:3)

试试这个 -

ALTER PROCEDURE [dbo].[addApp] 

      @Name VARCHAR(50)
    , @logoUrl VARCHAR(150)
    , @siteUrl VARCHAR(150)
    , @userId INT
    , @canvasWidth INT
    , @canvasHeight INT

AS BEGIN

    DECLARE @tempId INT

    INSERT INTO dbo.AppInfo (name, logoUrl, userId) 
    SELECT @Name, @logoUrl, @userId

    SELECT @tempId = SCOPE_IDENTITY()

    INSERT INTO dbo.CanvasApps (id, siteUrl, canvasWidth, canvasHeight) 
    SELECT @tempId, @siteUrl, @logoUrl, @userId

END 

答案 2 :(得分:2)

在插入语句后尝试此操作,并将此变量用于第二个插入语句。: -

SET @BVar=SCOPE_IDENTITY() 

答案 3 :(得分:1)

您需要将output的结果放入表中,而不仅仅是标量变量:

declare @tempId table (
    id int
)

INSERT INTO AppInfo (name, logoUrl, userId) 
       OUTPUT inserted.id into @tempId 
              VALUES(@Name, @logoUrl, @userId);

答案 4 :(得分:0)

只需使用以下变量:

@@IDENTITY

答案 5 :(得分:0)

ALTER PROCEDURE [dbo].[addApp] 
  @Name varchar(50),  
  @logoUrl varchar(150), 
  @siteUrl varchar(150), 
  @userId int, 
  @canvasWidth int, 
  @canvasHeight int
AS
BEGIN
  SET NOCOUNT ON;

  INSERT dbo.AppInfo (name, logoUrl, userId) 
    OUTPUT inserted.id, @siteUrl, @canvasWidth, @canvasHeight
      INTO dbo.CanvasApps(id, siteUrl, canvasWidth, canvasHeight)
    SELECT @Name, @logonUrl, @userId;
END
GO