views:

52

answers:

3

Why does

left(FIELD, replace(nullif(charindex('-', FIELD), 0), null, len(FIELD)))

always return null? The idea behind the query is that if charindex() returns 0, then convert the results into null, then convert the null into the length of the field. So if '-' does not exist, show the whole string. For some reason it makes every row equal null.

Thank you.

A: 

So, if field contains "-", show length. If no "-", show field?

CASE
    WHEN FIELD NOT LIKE '%-% THEN FIELD
    ELSE CAST(LEN (FIELD) AS varchar(4))
END

You need the cast to avoid datatype precedence

Flip the condition if you want NULL FIELD to work differently (it will go to the ELSE clause)

gbn
I'm not sure what the OP is asking, but you need another `)` on the end of your ELSE case.
KM
@KM: thanks, corrected
gbn
+1  A: 

Because REPLACE() returns NULL if any one of the arguments is NULL. Says so in the docs.

Do this instead:

select isnull(nullif(charindex(' ',field),0),len(field))
JC
A: 

When you say then convert the null into the length of the field, do you mean convert Nulls into a series of spaces like so:

Select
    Case
    When Field Like '%-%' Then Replicate(' ', Len(Field))
    Else Field
    End
Thomas