我有这个过程作为T-SQL脚本的一部分被删除/创建 - 想法是插入父记录,并将其ID输出到调用者,以便我可以插入<使用该ID的em> children 记录。
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
当我 debug 脚本并逐行执行时,我可以看到dbo.InsertCategory
正确地分配了@id
输出参数,脚本看作{{1}问题是@categoryId
总是@categoryId
,因此我没有将任何内容插入null
。
我做错了什么?
答案 0 :(得分: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