I have this procedure that is discarded / created as part of a T-SQL script. The idea is to insert the parent record and display its identifier to the caller so that I can insert records using this identifier.
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
Then a little further down the script it is called like this:
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
When I debug the script and step by line, I see that it dbo.InsertCategoryassigns the @idout parameter correctly , which the script sees as @categoryId- the problem is @categoryIdalways null, and therefore I do not get anything inserted into dwd.SubCategories.
What am I doing wrong?