【问题标题】:Checking for a string within a string, and not in another string using SQL使用 SQL 检查字符串中的字符串,而不是另一个字符串
【发布时间】:2014-03-12 18:30:25
【问题描述】:

我正在尝试构建一个简短的 SQL 脚本来检查 @NewProductAdded 是否在 @NewTotalProducts 中的某个位置。如果@NewProductAdded 不在@OldTotalProducts 中。请看下面的设置(真实数据在表格中,不是变量,但我只需要一个简单的例子):

declare @NewProductAdded as varchar(max)
declare @NewTotalProducts as varchar(max)
declare @OldTotalProducts as varchar(max)

set @NewProductAdded ='ProductB'
set @NewTotalProducts = 'ProductAProductBProductC'
set @OldTotalProducts = 'ProductAProductC'

SELECT CustomerID FROM Products WHERE NewProductAdded ... 

我想确保“ProductB”包含在@NewTotalProducts 中的某个位置,而不包含在@OldTotalProducts 中的任何位置。产品名称因数以千计的组合而千差万别,并且无法在一个字符串中真正将它们彼此分开。我确信有一个简单的解决方案或功能,我只是还不知道。

【问题讨论】:

  • 您使用的是什么 RDBMS(SQL Server、MySQL 等)?
  • WHERE CHARINDEX(@NewProductAdded, @NewTotalProducts) > 0 AND CHARINDEX(@NewProductAdded, @OldTotalProducts) = 0

标签: sql string compare product


【解决方案1】:

您的问题的具体答案是like(或charindex(),如果您使用的是SQL Server 或Sybase):

where @NewTotalProducts like '%'+@NewProductAdded+'%' and
      @OldTotalProducts not like '%'+@NewProductAdded+'%'

第一条评论。如果您必须使用存储在字符串中的列表,至少使用分隔符:

where ','+@NewTotalProducts+',' like '%,'+@NewProductAdded+',%' and
      ','+@OldTotalProducts+',' not like '%,'+@NewProductAdded+',%'

第二条评论。不要将列表存储在字符串中。而是使用临时表或表变量:

declare @NewTotalProducts table (name varchar(255));

insert into @NewTotalProducts(name)
    select 'ProductA' union all
    select 'ProductB' . . .

注意:在整个答案中,我使用了 SQL Server 语法。代码似乎是 SQL Server。

【讨论】:

  • 谢谢,这证实了我最初认为我应该使用的 LIKE 比较。但我不知道变量或表列可以像您的示例一样嵌套在其中。是的,相信我,我不喜欢字符串中的列表,但我们的客户使用的是旧系统,这就是我们必须处理的方式。你的例子很有帮助,谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-05-11
  • 2011-02-07
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多