-5

I am writing a piece of code where @Variant is provided. I wanted to store multiple values by capturing them in a variable (runtime) and pass them in the WHERE clause. Share the logic

DECLARE @Variant VARCHAR(50)
SET @Variant='''25'',''33'''
SELECT @Variant  ---- which is actually '25','33'
SELECT 'TRUE' WHERE '25' IN (@Variant)

DECLARE @Variant VARCHAR(50)
SET @Variant='''25'',''33'''
SELECT @Variant  ---- which is actually '25','33'
SELECT 'TRUE' WHERE '25' IN (SELECT @Variant)

Above queries do not work...

--DECLARE @Variant VARCHAR(50)
--SET @Variant='''25'',''33'''
--SELECT @Variant
SELECT 'TRUE' WHERE '25' IN ('25','33')

Above is a simpler query in SQL Server -which I tried if SQL accepts. My actual query is to pass wild cards in the LIKE statement in WHERE clause.

DECLARE @Variant VARCHAR(50) SET @Variant='''25%'' OR [Item_No] LIKE ''33%''' SELECT @Variant
SELECT * from Table1 WHERE [Item_No] LIKE (@Variant) --I presume @variable will be replaced with its value during execution.

Anyways, simpler way - I have a Item_No in the Where clause to which i want to supply multiple wild cards. Is there a method similar to inline function, which should replace the text at the @variant and execute combining it.

Ravi
  • 9
  • 1
  • 1
  • 4

2 Answers2

2
DECLARE @Variant VARCHAR(50)
SET @Variant='''25'',''33'''

At this point @Variant contains a single string.

SELECT 'TRUE' WHERE '25' IN (@Variant)

Given the 25 does not equal '25','33' this is never going to match. (IN is looking for an exact match – equality – with at least one of the set of values supplied in the parentheses.)

SQL will not magically parse a string into a collection. You'll need to tell it to. Options to do this depend on the particular DBMS you are using. They include temporary tables and table valued variables.

Richard
  • 106,783
  • 21
  • 203
  • 265
  • Thanks Richard - your explanation "Given the 25 does not equal '25','33' this is never going to match" – Ravi Jun 22 '16 at 10:05
0

SQL Like condition will work in your scenerio.

DECLARE @Variant VARCHAR(50)
SET @Variant='''25'',''33'''

SELECT 'TRUE' WHERE @Variant like '%25%'

Here result is TRUE. Hope this will help.

Tasawar
  • 541
  • 4
  • 20