String.IsNullOrEmpty like function for VARCHARs in SQL?

前端 未结 10 1870
一个人的身影
一个人的身影 2021-02-12 11:10

Say I\'ve got a function or stored procedure that takes in several VARCHAR parameters. I\'ve gotten tired of writing SQL like this to test if these parameters have a value:

10条回答
  •  野的像风
    2021-02-12 11:48

    You don't need to check for null before calling LEN. You can just use LEN(@SomeVarcharParm) > 0. This will return false if the value is NULL, '', or ' '. This is because NULL > 0 returns false. See for yourself run:

    SELECT 
     CASE WHEN NULL > 0 THEN 'NULL > 0 = true' ELSE 'NULL > 0 = false' END,
     CASE WHEN LEN(NULL) > 0 THEN 'LEN(NULL) = true' ELSE 'LEN(NULL) = false' END,
     CASE WHEN LEN('') > 0 THEN 'LEN('''') > 0 = true' ELSE 'LEN('''') > 0 = false' END,
     CASE WHEN LEN(' ') > 0 THEN 'LEN('' '') > 0 = true' ELSE 'LEN('' '') > 0 = false' END,
     CASE WHEN LEN(' test ') > 0 THEN 'LEN('' test '') > 0 = true' ELSE 'LEN('' test '') > 0 = false' END
    

提交回复
热议问题