2010-10-08 27 views
0

我有以下插入存儲過程:簡化SQL插入其使用NEWSEQUNETIALID()柱默認

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簡化爲一條簡潔的語句。我希望這有幫助。

0

由於newsequentialid()只能用作列缺省值,則可以將原始查詢更改爲:

  • 插入只是@ServerEnvironmentId如果沒有值已供應,從而產生新的順序ID和從OUTPUT條款取回

  • 然後更新由要麼@ServerEnvironmentId定義該行最初傳遞,或者你只是通過插入一個「虛擬行」到表

  • 012創建的新ID

不知道這是否會更快/更高效 - 您必須對此進行一些測量。