Quantcast
Channel: SQLServerCentral » SQL Server 2014 » Development - SQL Server 2014 » Latest topics
Viewing all articles
Browse latest Browse all 3145

Selective updates to NULL

$
0
0
OK, some Friday fun.Here's a set-up script:[code="sql"]IF OBJECT_ID('tempdb..#test', 'U') IS NOT NULL DROP TABLE #test;CREATE TABLE #test ( Id INT PRIMARY KEY ,Flag BIT NULL );INSERT #test (Id, Flag)VALUES (1, 0), (2, NULL);SELECT *FROM #test t;[/code]Now, let's assume I want to build some code to update the Flag column. I might start with something like this:[code="sql"]DECLARE @Id INT = 1;DECLARE @Flag BIT = NULL;UPDATE #testSET Flag = @FlagWHERE Id = @Id;SELECT *FROM #test t;[/code]Does the job, right?But, being a thoughtful developer, I want to perform the update only if the value of Flag is being changed. The fact that Flag is nullable (and that it might have a value which I want to set back to NULL), suggests that I have to write code like this (note that as SET ANSI_NULLS OFF is deprecated, I don't want to use that).[code="sql"]DECLARE @Id INT = 2;DECLARE @Flag BIT = NULL;UPDATE #testSET Flag = @FlagWHERE Id = @Id AND ( Flag <> @Flag OR ( Flag IS NULL AND @Flag IS NOT NULL ) OR ( Flag IS NOT NULL AND @Flag IS NULL ) );[/code]I know that this could be modeled differently using, for example, a non-nullable Tinyint having (-1,0,1) as possible values, but is there a tidier solution for the nullable Bit problem described above?

Viewing all articles
Browse latest Browse all 3145

Latest Images

Trending Articles



Latest Images