0

我有以下插入存储过程:

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()over的性能改进,它只能作为表列级别的默认值提供。newid(). newsequentialid()newid()

任何关于简化原始查询但利用的想法newsequentialid()?或者,原始查询是实现这一目标的最简化的解决方案吗?

4

3 回答 3

0

是的。考虑尝试新的合并语句。它应该与 newsequentialid() 的列默认值 100% 兼容,并将 SQL 简化为一条简洁的语句。我希望这有帮助。

于 2010-10-08T05:46:14.053 回答
0

由于newsequentialid()只能用作列默认值,您可以将原始查询更改为:

  • 仅插入@ServerEnvironmentIdif 没有提供值,从而生成一个新的顺序 ID 并从OUTPUT子句中检索它

  • 然后@ServerEnvironmentId通过将“虚拟行”插入表中来更新由最初传入的或刚刚创建的新 ID定义的行

不确定这是否会更快/更有效-您必须对此进行一些测量。

于 2010-10-08T05:47:29.117 回答
0

我最初的想法是正确的。这是最简单和最易读的解决方案。

于 2010-10-10T11:20:08.180 回答