0

I'm trying to figure out how to create a var in Sql Server which contains an array of values, searched here in Stack but nothing consistent... this is how I imagined it could be like:

declare @partners as nvarchar(max) = ('partner1','partner2');
select * from partners
where partner in (@partners);

Is it possible in SQL Server? How?

Thanks!

Ralph
9,4544 gold badges35 silver badges42 bronze badges
asked Oct 19, 2017 at 9:54

3 Answers 3

3

You can do it with table

declare @partnersList as table(partnerName varchar(100))
insert into @partnersList values('partner1'),('partner2')
SELECT * 
FROM partners
WHERE 'partner' in (SELECT partnerName FROM @partnersList)
answered Oct 19, 2017 at 10:00

1 Comment

Disappointed that SQL Server do not support this kind of logic, but this solution is useful and solved my problem, thank you!
2

You can't do so, but you can use a table variable to get the same behavior:

declare @partners TABLE (
 Name nvarchar(max)
)
INSERT @partners
VALUES
 ('partner1'),
 ('partner2')
select * from partners
where partner in (
 SELECT Name 
 FROM @partners
)
answered Oct 19, 2017 at 10:01

Comments

2

Or you can execute it as dynamic:

declare @partners as nvarchar(max) = ' ''partner1'',''partner2'' '
declare @sql nvarchar(Max)
Set @sql='SELECT * FROM partners WHERE [partner] IN ('+ @partners +')'
exec sp_executesql @sql
answered Oct 19, 2017 at 10:05

1 Comment

This exposes the code to SQL injection and should be, really, the very last resort.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.