1

I am trying to remove the "s" from the word "years" when the COUNT() is < 2 but my syntax is not right for some reason:

Errors: Incorrect syntax near the keyword 'IF'. Incorrect syntax near the keyword 'convert'.

stuff(
        (
        select ',' + Related_name + ' (' + (select
        IF COUNT(begin_date) > 1 BEGIN convert(varchar(10), COUNT(begin_date))  + ' years)' END
        ELSE BEGIN convert(varchar(10), COUNT(begin_date))  + ' year)'
        from cus_relationship subInnerR
        where subInnerR.master_customer_id = c.master_customer_id
        and subInnerR.related_master_customer_id = innerR.related_master_customer_id
        and subInnerR.relationship_type = 'ADVSPR'
        and subInnerR.relationship_code = 'CLUB'
        and subInnerR.reciprocal_code = 'FACADV')
        from cus_relationship innerR
        where [...]
1
  • 1
    You can better use case instead of if.... Commented Sep 18, 2013 at 14:46

4 Answers 4

2

Try like this(As commented by gvee in comments as this reduces some repeated code!!):-

 select ',' + Related_name + ' (' + (select
    Convert(varchar(10), Count(begin_date)) + ' year' + 
    CASE WHEN Count(begin_date) > 1 THEN 's'    ELSE '' END + ')'
    from cus_relationship subInnerR
    where subInnerR.master_customer_id = c.master_customer_id
    and subInnerR.related_master_customer_id = innerR.related_master_customer_id
    and subInnerR.relationship_type = 'ADVSPR'
    and subInnerR.relationship_code = 'CLUB'
    and subInnerR.reciprocal_code = 'FACADV')
    from cus_relationship innerR
    where [...]
Sign up to request clarification or add additional context in comments.

1 Comment

You forgot the + ')' after the CASE statement =D
1

Maybe this helps

In tsql you use CASE instead of IF

Comments

1

I am not a fan of reusing the same code, so I'd use CASE like this:

CONVERT(VARCHAR(10), COUNT(begin_date)) 
+ ' year' 
+ CASE WHEN COUNT(begin_date) > 1 THEN 's' ELSE '' END
+ ')'

split out on multiple lines for readability

Comments

0

You'll need to do this with a CASE statement instead of IF:

case
    when COUNT(begin_date) > 1 then
        convert(varchar(10), COUNT(begin_date))  + ' years)'
    else
        convert(varchar(10), COUNT(begin_date))  + ' year)'
end

1 Comment

Quick thought to reduce repeated code: Convert(varchar(10), Count(begin_date)) + ' year' + CASE WHEN Count(begin_date) > 1 THEN 's' ELSE '' END

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.