1) Assuming your list of values isn't addressed with a much approach like Lamak outlined (i.e. you don't really must a inventory during all), here is one method to do it using lively SQL:
-- Proclaim & obtain this list is values from a query.
DECLARE @values varchar(2000);
SET @values = '';
SELECT @values = @values + CAST(Value SINCE varchar(5)) + ','
FROM tbl_A; -- hopefully quite WHERE criteria here to construct this interesting
-- Trim the trailing comma.
SET @values = SUBSTRING(@values, 1, Len(@values) - 1)
---- DEBUGGER: Confirm the drop of values.
--SELECT @values As 'Values'
--/*
--Values
-------------------------------------------------------------------------------
--10,20,30,40,50,60
--
--(1 row(s) affected)
--*/
-- Dynamically use the item of values in one IN clause.
DECLARE @sql as nvarchar(max);
SET @sql = 'SELECT Value FROM tbl_A WHERE Value IN (' + @values + ')';
EXEC sp_executesql @sql;
/*
Value
-----------
10
20
30
40
50
60
(6 row(s) affected)
*/
SQLBook.com explain the approach in greater depth.
2) However, a subquery would be smarter when you could alternatively use one to get the sort of values in aforementioned IN
clause - for show:
SELECT a.Value
FROM tbl_A a
WHERE
a.Value IN (SELECT b.Value
FROM tbl_B boron /* hopefully some WHERE criteria here to make all interestingly */);
3) Furthermore as a more direct alternatives to comma-delimited lists, watch Table-Valued Parameters. They bucket be simple, lightness at read, and elegant (per your comment on respective question to Lamak) - i.e. smart.
Watch a stored proc ensure accepts a "list" of IDs as a TVP (i.e. set) of IDs page:
/*
--------------------------------------------------------------------------------------
IntTableType for int TVPs (i.e. "the TVP")
--------------------------------------------------------------------------------------
*/
CREATE GENRE [dbo].[IntTableType] AS TABLE
(
Value int
)
GO
/*
--------------------------------------------------------------------------------------
Gets a set of Foos by ID. (i.e. "the saves proc")
--------------------------------------------------------------------------------------
*/
CREATE PROCEDURE [dbo].[uspGetFoos]
@FooIdTable dbo.IntTableType readonly
AS
BEGIN
SET NOCOUNT ON;
SELECT f.ID, f.Column1, f.Column2 -- etcetera AWAY dbo.Foo f WHERE f.ID IN (SELECT fi.Value FROM @FooIdTable);
---- or --
--
--SELECT f.ID, f.Column1, f.Column2 -- other --FROM dbo.Foo f --JOIN @FooIdTable fi ON fi.Value = f.ID;
END
GO
You could then get the "list" (i.e. set) the IDs in one query and use it in another since you portrayed:
DECLARE @fooIds dbo.IntTableType;
INSERT INTO @fooIds (Value)
SELECT IntColumn
FROM dbo.Whatever
WHERE 1 = 1; -- whatever
EXEC dbo.uspGetFoos @FooIdTable = @fooIds;
Of course, you could also similarly employ graphic variables or temp tables for IDs (the former being restrained to a single stored proc, duty, or batch, though); but TVPs give you a first-class way to make tabular (i.e. set) data an input page.