Link to home
Start Free TrialLog in
Avatar of Karuppaiah
Karuppaiah

asked on

In clause in SQL Query

Hi,
In the below two queries, first one returns 2 records and the second one returns no records. How do I make the second query work?

--Query 1
Select * from MediaOwners where MediaOwnerName in ('Viacom','Lamar')

--Query 2
declare @x varchar(100)
set @x='''Viacom'',''Lamar'''
print @x
Select * from MediaOwners where MediaOwnerName in (@x)
ASKER CERTIFIED SOLUTION
Avatar of robertjbarker
robertjbarker
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Another way:

declare @x varchar(100)
set @x='''Viacom'',''Lamar'''

declare @xs varchar(1000)
set @xs = 'Select * from MediaOwners where MediaOwnerName in (' + @x +')'
exec (@xs)
-- one more possibility, if @x members are unique
declare @x varchar(100)
set @x='''Viacom'',''Lamar'''
print @x
Select * from MediaOwners where @x like ( '%'''+ MediaOwnerName + '''% ')
Avatar of Lowfatspread
or of course parse the inlist string into separate components
(if you'll allow only a fixed number) and

select *
from ..
where yyy in (@x1.@x2,@x3,...),
Avatar of fds_fatboy
fds_fatboy

How about something like (bear with the typos, I haven't got SQL Server on this machine)

--First create a new (reusable UDF) to split the string up.
CREATE FUNCTION dbo.fnSplitString(@MyString varchar(8000),@delimiter char(1))
RETURNS @SplitString TABLE
(
    string varchar(8000)
)
AS
BEGIN
    DECLARE @chindex int
    @chindex = CHARINDEX(@delimiter,@MyString)
    WHILE @chindex > 0
    BEGIN
        INSERT INTO @SplitString
        VALUES(LEFT(@MyString,@chIndex -1))
        SET @MyString = SUBSTRING(@MyString,chIndex+1,8000)
    END
    INSERT INTO @SplitString
    VALUES(@MyString)
    RETURN
END

-- Then alter your original query thus:
declare @x varchar(100)
set @x='Viacom,Lamar'
print @x
Select * from MediaOwners where MediaOwnerName in (SELECT string FROM dbo.fnSplitString(@x), ",")


Sorry, that last line should have read:

Select * from MediaOwners where MediaOwnerName in (SELECT string FROM dbo.fnSplitString(@x.','))
hmmmm ... wouldn't this work ... just build a TSQL string composed with the appropriate quotes and execute?

declare @MySqlRaw varchar(1000)
SET @MySqlRaw = 'Select * from MediaOwners where MediaOwnerName in (' + ''''Viacom'',''Lamar''' + ')'
EXEC (@MySqlRaw)

(p.s. not sure I have the single quotes balanced in above but you get the idea)

>>wouldn't this work<<
Yes, but it requires using dynamic SQL.  This implies bad performance and lousy security (you must give the user Select permissions for the table).