Sql server 简化使用newSequentialid()列默认值的SQL插入
我有以下insert存储过程:Sql server 简化使用newSequentialid()列默认值的SQL插入,sql-server,insert,default,newsequentialid,Sql Server,Insert,Default,Newsequentialid,我有以下insert存储过程: CREATE Procedure dbo.APPL_ServerEnvironmentInsert ( @ServerEnvironmentName varchar(50), @ServerEnvironmentDescription varchar(1000), @UserCreatedId uniqueidentifier, @ServerEnvironmentId uniqueidentifier OUTPUT ) WITH
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()?或者,原始查询是实现这一点最简单的解决方案吗?是。考虑试一试。它应该与newsequentialid()的默认列100%兼容,并且它将把SQL简化为一条简洁的语句。我希望这会有所帮助。由于newsequentialid()
只能用作列默认值,因此您可以将原始查询更改为:
- 如果没有提供值,则只插入
@ServerEnvironmentId
,从而生成一个新的顺序ID,并从输出
子句中检索它
- 然后更新由最初传入的
@ServerEnvironmentId
定义的行,或通过在表中插入“虚拟行”创建的新ID
不确定这是否会更快/更有效-您必须对此进行一些测量。我最初的想法是正确的。这是可能的最简单和最可读的解决方案