How to constraint no empty strings on an NVARCHAR column

后端 未结 6 824
悲&欢浪女
悲&欢浪女 2020-12-29 03:36

I add a NOT NULL constraint on my NVARCHAR column so it couldn\'t allow any empty values. but unfortunately SQL Server deals with NULL

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 03:45

    How about a check constraint that the column value doesn't equal an empty string? A bit cleaner than a trigger, and it can be modeled in code using many ORMs including NHibernate, so your app layer can be told to expect it.

    Failing that, when assigning the field you never want to be empty up in your application layer, try using a NullIfBlank() extension method:

    public static string NullIfBlank(this string input)
    {
       return String.IsNullOrWhitespace(input) ? null : input;
    }
    

    Null strings, empty strings, and strings that only contain spaces, newlines, tabspaces, etc will all come back as null. Now, this will require you to make sure you aren't doing any simple concatenations with this field that you don't also want to come back null: null + "any string" == null.

提交回复
热议问题