4

我正在编写一个存储过程,我首先在表中插入一个新行。此查询生成的 ID 随后需要用于另一个查询。是否可以使用 OUTPUT 访问预先生成的 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);
4

6 回答 6

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 
于 2013-04-22T12:55:29.623 回答
4

试试这个——

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 
于 2013-04-22T12:34:00.673 回答
2

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

SET @BVar=SCOPE_IDENTITY() 
于 2013-04-22T12:36:29.490 回答
1

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

declare @tempId table (
    id int
)

INSERT INTO AppInfo (name, logoUrl, userId) 
       OUTPUT inserted.id into @tempId 
              VALUES(@Name, @logoUrl, @userId);
于 2013-04-22T12:32:15.103 回答
0

只需使用以下变量:

@@IDENTITY
于 2013-04-22T12:28:47.477 回答
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
于 2013-04-22T12:56:01.653 回答