3

I have a char(15) NOT NULL column. I need to see if it is empty or contains all zeros. I can obviously do= '000000000000000' But is there a way using LIKE so its not hard coded to 15? I don't see why the [^0] below doesn't match all zeros.

CASE WHEN LTRIM(RTRIM(IL.ItemNumber)) = '' THEN 1 ELSE 0 END IsEmpty
CASE WHEN LTRIM(RTRIM(IL.ItemNumber)) <> '' AND LTRIM(RTRIM(IL.ItemNumber)) NOT LIKE '[^0]' THEN 1 ELSE 0 END IsZeros

I'm basically trying to validate the column. Trimming works for empty, but maybe there is a much cleaner/flexible way to accomplish both of these validations? Thanks!

1
  • [^0] matches only a single character, and this is because of the definition of the patterns used with LIKE. Commented Sep 9, 2013 at 13:53

1 Answer 1

8

Actually there is REPLICATE() function:

WHERE <column> = REPLICATE('0',15)

Funny thing, it's actually using 17 characters, exactly the same as the '000000000000000' literal.

(Reading again the question, I suppose you don't want the above either because it has the 15 hard coded.)


The LIKE condition you have is not working as expected because the LIKE '[^0]' would be true only if the column had exactly 1 character. I think you need to check if it has only 0s or not:

WHERE <column> NOT LIKE '%[^0]%'

To check if it has only 0s or only spaces, this do (for CHAR and VARCHAR columns) and you don't even have to trim the column:

WHERE <column> = '' 
   OR <column> NOT LIKE '%[^0]%'
9
  • Right, maybe I should of expanded in my question. This is raw data. So before this process, I'm padding/zero-filling (using replicate) the value if it is not empty. Commented Sep 9, 2013 at 13:22
  • Nice, that seems to work. I wish there was an elegant way to check for all zero and empty in the same LIKE clause, but reading through the msdn it doesn't look possible. Thanks for your help! Commented Sep 9, 2013 at 13:52
  • Nevermind, I think %[^0 ]% will work for empty as well. Seriously, thanks! Commented Sep 9, 2013 at 13:57
  • Yes, but it will also allow strings like '00 000 00 ' Commented Sep 9, 2013 at 14:06
  • 1
    Use the @ypercubes answer above for performance but I thought I'd throw this out there: WHERE len(replace(<column>, '0','') = 0
    – Rob
    Commented Mar 15, 2017 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.