0

I'm trying to pass a value from a table into a variable which I can then use in a query. The problem is that I need the variable to have multiple values, which I've never done before. Below is an example of what I'm trying to do.

CompanyID has multiple values for control number. How would I be able to pass multiple values into the variable? The query I'm using is using Open Query so I can't join to a temp table.

 declare @t table( companyid int, control_number int)
 insert into @t
 values(5555, 777),
 (5555, 720),
 (5555, 234),
 (111, 345),
 (111, 356)

 select *
 from @t

 declare @CN int
 set @CN = (select control_number from @t where companyid = 5555)

 select *
 from @table
 where control_number IN(@CN)
jackstraw22
  • 517
  • 10
  • 30

3 Answers3

0

Instead of setting it into variable you can directly use it IN like this :

declare @t table( companyid int, control_number int)
 insert into @t
 values(5555, 777),
 (5555, 720),
 (5555, 234),
 (111, 345),
 (111, 356)

 select *
 from @t

 select *
 from @table
 where control_number IN(select control_number from @t where companyid = 5555)

Try this out I haven't able to run this because you haven.t shared schema of @table

Hammad Shabbir
  • 722
  • 1
  • 6
  • 13
0

Another way to skin the cat. Make your second variable a table variable. Then just join to it.

declare @CN table (cntNbr int)
insert @CN (cntNbr)
select control_number from @t where companyid = 5555;

select t.*
from @t as t
join @CN as c
  on c.cntNbr = t.control_number;

Rextester link: https://rextester.com/SCYCX42852

Eric Brandt
  • 7,886
  • 3
  • 18
  • 35
0

Method 1 (Dynamic SQL):

CREATE TABLE #temp ( companyid INT, control_number INT )
INSERT INTO #temp
VALUES (5555, 777),
(5555, 720),
(5555, 234),
(111, 345),
(111, 356)

SELECT * FROM #temp

DECLARE @controlNum VARCHAR(MAX)
SELECT @controlNum = ISNULL(@controlNum + ', ', '') + CAST(control_number AS VARCHAR) FROM #temp WHERE companyid = 5555

DECLARE @sql NVARCHAR(MAX) = 'SELECT * FROM #temp WHERE control_number IN ( ' + @controlNum + ')'
EXEC sp_executesql @sql

Method 2:

DECLARE @temp TABLE( companyid INT, control_number INT )
INSERT INTO @temp
VALUES (5555, 777),
(5555, 720),
(5555, 234),
(111, 345),
(111, 356)

SELECT * FROM @temp

SELECT * FROM @temp WHERE control_number IN (SELECT control_number FROM @temp WHERE companyid = 5555)
Nayanish Damania
  • 542
  • 5
  • 13