【问题标题】:Select Query is not working with in Clause选择查询在子句中不起作用
【发布时间】:2018-09-10 05:46:39
【问题描述】:

如果我们将值 In 子句从 'Canada,Portugal' 转换为 'Canada','Portugal' 传递,则 SQL 查询不起作用 如果在子句 'Canada','Portugal' 中通过硬编码值,它会起作用

  declare @GeographicalLocation varchar(max) 
        set @GeographicalLocation ='Canada,Portugal'
        set @GeographicalLocation  = REPLACE(@GeographicalLocation, ',', ''',''')
        set @GeographicalLocation = ''''+@GeographicalLocation+'''';
select ContinentName from [ContinentList] where ContinentId in 
    (select ContinentId from [CountryList] where [CountryName] 
     in(@GeographicalLocation)and BaseId is Null)

【问题讨论】:

  • 你应该试试split()函数并加入它。
  • 为什么不工作?
  • 您不是在传递一个列表,而是在传递一个包含值 Canada,Portugal 的字符串,并且不能在 in 子句中使用字符串

标签: sql-server no-response


【解决方案1】:

因为,最后你的where 子句看起来像:

where [CountryName] in ('''Canada'',''Portugal''')

where caluse 中的这个字符串应该是两个单独的字符串,但它只有一个!它应该是这样的:

where [CountryName] in ('Canada','Portugal')

所以,对于这种情况,我会使用类似的东西

where charindex([CountryName], @GeographicalLocation) > 0

在这种方法中,您不需要将额外的' 附加到您的字符串变量中。 我建议使用区分大小写的排序规则。

【讨论】:

    猜你喜欢
    • 2015-10-25
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    相关资源
    最近更新 更多