我有以下插入存储过程:
CREATE Procedure dbo.APPL_ServerEnvironmentInsert
(
@ServerEnvironmentName varchar(50),
@ServerEnvironmentDescription varchar(1000),
@UserCreatedId uniqueidentifier,
@ServerEnvironmentId uniqueidentifier OUTPUT
)
WITH RECOMPILE
AS
-- Stores the ServerEnvironmentId.
DECLARE @APPL_ServerEnvironment TABLE (ServerEnvironmentId uniqueidentifier)
-- If @ServerEnvironmentId was not supplied.
IF (@ServerEnvironmentId IS NULL)
BEGIN
-- Insert the data into the table.
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId
)
OUTPUT Inserted.ServerEnvironmentId INTO @APPL_ServerEnvironment
VALUES
(
@ServerEnvironmentName,
@ServerEnvironmentDescription,
GETDATE(),
@UserCreatedId
)
-- Get the ServerEnvironmentId.
SELECT @ServerEnvironmentId = ServerEnvironmentId
FROM @APPL_ServerEnvironment
END
ELSE
BEGIN
-- Insert the data into the table.
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentId,
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId
)
VALUES
(
@ServerEnvironmentId,
@ServerEnvironmentName,
@ServerEnvironmentDescription,
GETDATE(),
@UserCreatedId
)
END
GO
我可以简化以上内容:
CREATE Procedure dbo.APPL_ServerEnvironmentInsert
(
@ServerEnvironmentName varchar(50),
@ServerEnvironmentDescription varchar(1000),
@UserCreatedId uniqueidentifier,
@ServerEnvironmentId uniqueidentifier OUTPUT
)
WITH RECOMPILE
AS
-- Ensure @ServerEnvironmentId IS NOT NULL
SELECT ISNULL(@ServerEnvironmentId, newid())
-- Insert the data into the table.
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentId,
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId
)
VALUES
(
@ServerEnvironmentId,
@ServerEnvironmentName,
@ServerEnvironmentDescription,
GETDATE(),
@UserCreatedId
)
GO
但是,通过这样做,我失去了newsequentialid()
超过newid().
newsequentialid()
的性能改进,无法在代码中设置为newid()
,它只能作为提供表列级别的默认值。
任何人都在想简化原始查询但使用newsequentialid()
?或者,原始查询是实现此目的最简化的解决方案吗?
答案 0 :(得分:0)
是。考虑尝试new merge statement。它应该与newsequentialid()的列默认值100%兼容,并且它将SQL简化为一个简洁的语句。我希望这会有所帮助。
答案 1 :(得分:0)
由于newsequentialid()
只能用作列默认值,因此您可以将原始查询更改为:
如果没有提供任何值,只插入@ServerEnvironmentId
,从而生成新的序列ID并从OUTPUT
子句中检索
然后更新由最初传入的@ServerEnvironmentId
定义的行,或者通过在表中插入“虚拟行”来创建刚刚创建的新ID
不确定这是否更快/更有效 - 你必须对此进行一些测量。
答案 2 :(得分:0)
我最初的想法是正确的。它是最简单,最易读的解决方案。