Is there a way to make a TSQL variable constant?

前端 未结 12 1043
别那么骄傲
别那么骄傲 2021-02-01 11:31

Is there a way to make a TSQL variable constant?

12条回答
  •  [愿得一人]
    2021-02-01 12:19

    Prior to using a SQL function run the following script to see the differences in performance:

    IF OBJECT_ID('fnFalse') IS NOT NULL
    DROP FUNCTION fnFalse
    GO
    
    IF OBJECT_ID('fnTrue') IS NOT NULL
    DROP FUNCTION fnTrue
    GO
    
    CREATE FUNCTION fnTrue() RETURNS INT WITH SCHEMABINDING
    AS
    BEGIN
    RETURN 1
    END
    GO
    
    CREATE FUNCTION fnFalse() RETURNS INT WITH SCHEMABINDING
    AS
    BEGIN
    RETURN ~ dbo.fnTrue()
    END
    GO
    
    DECLARE @TimeStart DATETIME = GETDATE()
    DECLARE @Count INT = 100000
    WHILE @Count > 0 BEGIN
    SET @Count -= 1
    
    DECLARE @Value BIT
    SELECT @Value = dbo.fnTrue()
    IF @Value = 1
        SELECT @Value = dbo.fnFalse()
    END
    DECLARE @TimeEnd DATETIME = GETDATE()
    PRINT CAST(DATEDIFF(ms, @TimeStart, @TimeEnd) AS VARCHAR) + ' elapsed, using function'
    GO
    
    DECLARE @TimeStart DATETIME = GETDATE()
    DECLARE @Count INT = 100000
    DECLARE @FALSE AS BIT = 0
    DECLARE @TRUE AS BIT = ~ @FALSE
    
    WHILE @Count > 0 BEGIN
    SET @Count -= 1
    
    DECLARE @Value BIT
    SELECT @Value = @TRUE
    IF @Value = 1
        SELECT @Value = @FALSE
    END
    DECLARE @TimeEnd DATETIME = GETDATE()
    PRINT CAST(DATEDIFF(ms, @TimeStart, @TimeEnd) AS VARCHAR) + ' elapsed, using local variable'
    GO
    
    DECLARE @TimeStart DATETIME = GETDATE()
    DECLARE @Count INT = 100000
    
    WHILE @Count > 0 BEGIN
    SET @Count -= 1
    
    DECLARE @Value BIT
    SELECT @Value = 1
    IF @Value = 1
        SELECT @Value = 0
    END
    DECLARE @TimeEnd DATETIME = GETDATE()
    PRINT CAST(DATEDIFF(ms, @TimeStart, @TimeEnd) AS VARCHAR) + ' elapsed, using hard coded values'
    GO
    

提交回复
热议问题