Store Numbers of Value in One Variable in SQL

-- Suppose I have a Table which has n numbers of rows with different user IDs.
-- And I want the data of some particular users.
-- So we will write those user IDs in the where condition.
-- But sometimes what happens is that we tend to write the number of the lines, in the where condition, to get the user id.
-- So instead of doing that, you can make another query and store all that id in one variable.
-- You have two methods, either you can take the help of a temp table or use the following method given by me:
-- Declare a variable
declare @id varchar(max) ;
-- set variable
set @id =substring(
(
SELECT distinct ',' +cast(UserId as varchar)+'' from Users    --- here write your table and condition to get particular userid
for xml path('')
),2,8000)
declare @query varchar(max);
set @query =  'select * from Invoice where UserID in ('+@id+')'
execute(@query)     -- run your query
Ebook Download
View all
Learn
View all