Thursday, August 16, 2018

Check to see if a varchar type column is null or holding an empty string in T-SQL.

See the last line below. (The others are just setup for the last line.)

BEGIN TRANSACTION
GO
CREATE TABLE dbo.People
   (
   Id uniqueidentifier NOT NULL DEFAULT newid(),
   Name varchar(50) NOT NULL,
   [State] varchar(50),
   Country varchar(50) NOT NULL
   ) ON [PRIMARY]
GO
ALTER TABLE People ADD CONSTRAINT
   PK_CarPart PRIMARY KEY CLUSTERED
   (
   Id
   ) WITH( STATISTICS_NORECOMPUTE = OFF,
      IGNORE_DUP_KEY = OFF,
      ALLOW_ROW_LOCKS = ON,
      ALLOW_PAGE_LOCKS = ON)
COMMIT
INSERT INTO People (Name, [State], Country) VALUES ('Abe', 'Texas', 'United States')
INSERT INTO People (Name, Country) VALUES ('Jenny', 'Canada')
INSERT INTO People (Name, [State], Country) VALUES ('Karen', 'Minnesota', 'United
      States')
INSERT INTO People (Name, Country) VALUES ('Mike', 'Mexico')
INSERT INTO People (Name, [State], Country) VALUES ('Robbie', 'California', 'United
      States')
INSERT INTO People (Name, Country) VALUES ('Wendy', 'Canada')
INSERT INTO People (Name, [State], Country) VALUES ('Zach', 'Florida', 'United
      States')
GO
SELECT Id, Name, [State], CASE IsNull([State], '') WHEN '' THEN Country ELSE null
      END AS Country FROM People

 
 

This trick is a little like this one only it will also match on an empty string. In figuring this out I found this Stack Overflow article that has these examples of a slightly different shape:

  • Select *
    From Table
    Where (col is null or col = '')

     
  • Select *
    From Table
    Where IsNull(col, '') = ''

No comments:

Post a Comment