如何为SQL查询中的参数逐个传递多个值并将结果合并?

如何为SQL查询中的参数逐个传递多个值并将结果合并?

问题描述:

I have an SQL Statement which accepts a parameter @EndDate as DateTime. I want to be able to pass several values for @EndDate one by one and then Union the results of all the Queries. I have tried using CTE for this but it is of no use. I want to pass several Dates for @EndDate. Any help would be greatly appreciated.

My Query is:







DECLARE	@EndDate as DateTime
SET @EndDate = '2018/02/25'

SELECT  
CONVERT(VARCHAR, @EndDate, 101)  [R_Date]
,[Name] 	
[Type] 
FROM [dbo].[S_Table]




when @EndDate = '2018/02/24' 




R_Date	Name	Type
2/24/2018	A	Monthly
2/24/2018	A	Daily




<pre>when @EndDate = '2018/02/24' 




R_Date	Name	Type
2/25/2018	TEST_1	Monthly
2/25/2018	TEST_2	Monthly
2/25/2018	TEST_3	Daily
2/25/2018	TEST_4	Weekly
2/25/2018	TEST_5	Monthly
2/25/2018	TEST_6	Monthly
2/25/2018	TEST_7	Monthly
2/25/2018	TEST_8	Monthly
2/25/2018	TEST_9	Monthly
2/25/2018	TEST_10	Monthly





我的尝试:



我尝试了一个WHILE循环,但它会产生两个或多个结果,具体取决于重复次数。我希望结果作为单个查询结果可能是UNION ALL。



What I have tried:

I have tried a WHILE Loop but it will generate two or more results depending on the repetition. I want the result as a single query result may be a UNION ALL.

DROP TABLE IF EXISTS #TEMP;
CREATE #temp table(COLS..)
Declare  @filters table(id int identity(1,1),dt datetime);
Declare @cnt int=1;
WHILE(@cnt<=(select Count(*) from RealTable))
BEGIN
INSERT INTO #TEMP SELECT * FROM RealTable WHERE  DateCOL IN(SELECT DT from @filters WHERE ID=@cnt);
SET @CNT=@CNT+1;
END;
SELECT * FROM #Temp;