EmptyIf condition in SQL Server

Sheonarayan
Posted by Sheonarayan under Sql Server category on | Points: 40 | Views : 1397
I was facing a situation where if a database table column is empty, I need to set value as null otherwise the value of the column.

As there is no inbuilt function that does this, so here is the custom code for this.
   SELECT (CASE WHEN AuthorInfo = ''
THEN NULL
ELSE AuthorInfo END) AS AI FROM MyCategories


In this case, if AuthorInfo column is empty, its value will be set as NULL for AI column otherwise actual value of AuthorInfo will be set.

Comments or Responses

Posted by: Praveen_07 on: 7/17/2015 Level:Starter | Status: [Member] | Points: 10
I tried to reproduce the same and it's working perfectly fine

 CREATE TABLE #temp_table 
(
i INT,strvalue varchar(10)
)

INSERT STATMENTS :

  INSERT INTO #temp_table (i,strvalue) VALUES (1,' ');

INSERT INTO #temp_table (i,strvalue) VALUES (2,NULL);

INSERT INTO #temp_table (i,strvalue) VALUES (3,'HELLO');

QUERY :

  SELECT i,CASE strvalue WHEN '' 
THEN NULL
ELSE strvalue END AS AI FROM #temp_table



Login to post response