Language: SQL
Performance of SQL’s NullIf() Function (versus Case)
declare @x int, @y int, @z int set @x = 1 set @y = 2 set @z = 1 -- returns @x (because not equal) select case when @x = @y then null else @x end -- returns null (because equal) select case when @x = @z then null else @x end -- /// declare @x int, @y int, @z int set @x = 1 set @y = 2 set @z = 1 -- returns @x (because not equal) select NullIf(@x, @y) -- returns null (because equal) select NullIf(@x, @z) -- /// set nocount on print @@version declare @round int set @round = 0 while (@round < 3) begin set @round = @round + 1 print '' print 'round ' + convert(varchar, @round) declare @l int, @w int, @x int, @y int, @z int, @i int, @d datetime set @l = 1000000 set @x = 1 set @y = 2 set @z = 1 -- first, just warm up set @d = getdate() set @i = 0 while (@i < @l) begin set @w = nullif(@x, @y) set @w = nullif(@x, @z) set @w = (select case when @x = @y then null else @x end) set @w = (select case when @x = @z then null else @x end) set @i = @i + 1 end -- test nullif() set @d = getdate() set @i = 0 while (@i < @l) begin set @w = nullif(@x, @y) set @w = nullif(@x, @z) set @i = @i + 1 end print 'nullif(): ' + convert(varchar, datediff(ms, @d, getdate())) -- test case when set @d = getdate() set @i = 0 while (@i < @l) begin set @w = (select case when @x = @y then null else @x end) set @w = (select case when @x = @z then null else @x end) set @i = @i + 1 end print 'case when: ' + convert(varchar, datediff(ms, @d, getdate())) end -- ///
Tags:
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search

