我想创建一个插入记录并返回其主键的函数,以便我可以将该函数作为另一个查询的参数传递。例如,我尝试这样做:SQL函数返回一个包含INSERT的值
CREATE FUNCTION CreateEntity
(
@entityTypeId int,
@siteId int
)
RETURNS bigint
AS
BEGIN
DECLARE @entityId bigint;
INSERT INTO [ObjectSystem].[Entities] ([EntityTypeId], [SiteId], [Deleted])
VALUES (@entityTypeId, @siteId, 0);
SELECT @entityId = SCOPE_IDENTITY();
RETURN @entityId;
END
GO
但MSSMS凸显INSERT查询并说:“在一个函数中无效使用了副作用的运算符‘插入’的。”
我希望能够使用这样的功能,像这样:
INSERT INTO OtherTable (EntityId, Name, Description) VALUES
(CreateEntity(), 'Test', 'This is a test item.'),
(CreateEntity(), 'Test', 'This is a test item.'),
(CreateEntity(), 'Test', 'This is a test item.'),
(CreateEntity(), 'Test', 'This is a test item.'),
(CreateEntity(), 'Test', 'This is a test item.'),
(CreateEntity(), 'Test', 'This is a test item.');
我怎样才能达到预期的效果,如果在所有?如果不可能,我能做些什么呢?