Search code examples
t-sqlreplacenullnotnull

T-SQL Replace part of a not null column with NULL generates error


I have table variable and all its columns can not be null (NOT NULL definition for each):

DECLARE @SampleTable 
(
   ,SampleColumnID nvarchar(400) NOT NULL PRIMARY KEY
   ,SampleColumnText nvarchar(max) NOT NULL
)

I have done some operation with this variable and initialize the "SampleColumnText" with some text.

Then I try to replace some part of it with text return from other function. What happens is that the function returns NULL in some cases, so I this code generates me error:

REPLACE(SampleColumnText , '{*}', @InitByFunctionText)

WHERE @InitByFunctionText is NULL this time.

So, is it normal error to be generated as I am replacing only part of the text with NULL, not the whole text?


Solution

  • This is expected behaviour. REPLACE:

    Returns NULL if any one of the arguments is NULL.

    If you want to replace it with an empty string (which is not the same as NULL), you can use COALESCE:

    REPLACE(SampleColumnText , '{*}', COALESCE(@InitByFunctionText,''))