gpt4 book ai didi

tsql - Out 参数被正确分配,但调用者只看到一个 NULL。线索?

转载 作者:行者123 更新时间:2023-12-01 00:56:53 26 4
gpt4 key购买 nike

我有这个过程作为 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正确分配 @id out 参数,脚本将其视为 @categoryId - 问题是 @categoryId总是 null ,所以我没有在 dwd.SubCategories 中插入任何内容.

我究竟做错了什么?

最佳答案

您需要提及@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

关于tsql - Out 参数被正确分配,但调用者只看到一个 NULL。线索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27064948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com