4

我有这个作为 T-SQL 脚本的一部分被删除/创建的过程 - 想法是插入记录,并将其 ID 输出给调用者,以便我可以使用该 ID 插入记录。

if exists (select * from sys.procedures where name = 'InsertCategory')
    drop procedure dbo.InsertCategory;
go

create procedure dbo.InsertCategory
     @code nvarchar(5)
    ,@englishName nvarchar(50)
    ,@frenchName nvarchar(50)
    ,@timestamp datetime = null
    ,@id int output
as begin

    if @timestamp is null set @timestamp = getdate();

    declare @entity table (_Id int, EntityId uniqueidentifier);
    declare @entityId uniqueidentifier;

    if not exists (select * from dwd.Categories where Code = @code)
    insert into dwd.Categories (_DateInserted, Code, EntityId) 
        output inserted._Id, inserted.EntityId into @entity
        values (@timestamp, @code, newid());
    else
        insert into @entity
        select _Id, EntityId from dwd.Categories where Code = @code;

    set @id = (select _Id from @entity);
    set @entityId = (select EntityId from @entity);

    declare @english int;
    set @english = (select _Id from dbo.Languages where IsoCode = 'en');

    declare @french int;
    set @french = (select _Id from dbo.Languages where IsoCode = 'fr');

    exec dbo.InsertTranslation @entityId, @english, @englishName, @timestamp;
    exec dbo.InsertTranslation @entityId, @french, @frenchName, @timestamp;

end
go

然后再往下一点,它被称为这样的脚本:

declare @ts datetime;
set @ts = getdate();

declare @categoryId int;

exec dbo.InsertCategory 'C1', 'Category1', 'Catégorie1', @ts, @categoryId;
exec dbo.InsertSubCategory 'SC1', @categoryId, 'Description (EN)', 'Description (FR)', @ts

当我调试脚本并逐行执行时,我可以看到dbo.InsertCategory正确分配了@idout 参数,脚本将其视为@categoryId- 问题是@categoryId总是null,所以我没有将任何东西插入dwd.SubCategories.

我究竟做错了什么?

4

1 回答 1

4

您需要在调用过程时提及@categoryId参数,OUTPUT否则它不会返回值。像这样调用程序

exec dbo.InsertCategory 'C1', 'Category1', 'Catégorie1', @ts, @categoryId OUTPUT;

例子

CREATE PROCEDURE Procd (@a INT, @b INT output)
AS
  BEGIN
      SELECT @b = @a
  END

DECLARE @new INT

EXEC Procd 1,@new 
SELECT @new -- NULL

EXEC Procd 1,@new OUTPUT 
SELECT @new -- 1
于 2014-11-21T15:46:40.870 回答