我正试图删除" s"来自“#34; years"当COUNT()是< 2但我的语法由于某种原因不正确:
错误: 关键字' IF'附近的语法不正确。 关键字' 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 [...]
答案 0 :(得分:2)
尝试这样(在评论中由gvee评论,因为这减少了一些重复的代码!!): -
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 [...]
答案 1 :(得分:1)
在tsql中,您使用CASE
代替IF
答案 2 :(得分:1)
我不喜欢重复使用相同的代码,所以我会像这样使用CASE
:
CONVERT(VARCHAR(10), COUNT(begin_date))
+ ' year'
+ CASE WHEN COUNT(begin_date) > 1 THEN 's' ELSE '' END
+ ')'
为了便于阅读,在多行上拆分
答案 3 :(得分:0)
您需要使用CASE
语句而不是IF
来执行此操作:
case
when COUNT(begin_date) > 1 then
convert(varchar(10), COUNT(begin_date)) + ' years)'
else
convert(varchar(10), COUNT(begin_date)) + ' year)'
end