Question

I am trying to build a short SQL script that will check if @NewProductAdded is somewhere in @NewTotalProducts. And also if @NewProductAdded is NOT in @OldTotalProducts. Please have a look at the setup below (The real data is in tables, not variables, but a simple example is all I need):

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 ... 

I want to make sure that 'ProductB' is contained somewhere within @NewTotalProducts, and is NOT contained anywhere within @OldTotalProducts. Product names vary vastly with thousands of combinations, and there is no way to really separate them from each other in a string. I am sure there is a simple solution or function for this, I just don't know it yet.

Was it helpful?

Solution

The specific answer to your question is like (or charindex() if you are using SQL Server or Sybase):

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

First comment. If you have to use lists stored in strings, at least use delimiters:

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

Second comment. Don't store lists in strings. Instead, use a temporary tables or table variable:

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

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

Note: throughout this answer I have used SQL Server syntax. The code appears to be SQL Server.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top