We have an internal team who runs some queries on database every month to generate some reports. And queries remains same every time except varying date range. So I just want to automate this thing for them & to do so I need to write a stored procedure that can return data from multiple tables. Below is a small glimpse of what I am trying to do.
CREATE PROCEDURE TestProc
@StartDate datetime,
@EndDate datetime
AS
BEGIN
SELECT *
FROM abc
WHERE date BETWEEN @startdate AND @enddate
SELECT *
FROM xyz
WHERE date < @enddate
SELECT *
FROM def
WHERE date > @startdate
END
So basically I want data of above three queries to be returned to my calling application through TestProc
stored procedure. Is it possible to return multiple tables from a stored procedure?
If yes, then how & if not then is there any alternate option that I can use to meet my requirements?
Ideally I would write 3 separate procs to get data from 3 table but for some reason if you want 1 proc to do it all you can do something like:
Create procedure TestProc
@StartDate DATETIME = NULL,
@EndDate DATETIME = NULL,
@ResultSet VARCHAR(3)
AS
BEGIN
IF (@ResultSet = 'abc')
BEGIN
SELECT * from abc where date between @startdate and @enddate
END
ELSE IF (@ResultSet = 'xyz')
BEGIN
SELECT * from xyz where date <@enddate
END
ELSE IF (@ResultSet = 'def')
BEGIN
SELECT * from def where date > @startdate
END
ELSE
BEGIN
RAISERROR('Please pass a valid value to param @ResultSet, valid values are abc , xyz or def' , 16 ,1);
END
END
And call the proc 3 times with different @ResultSet
values to get the desired result set on each call.
As I remember
Create procedure TestProc
@StartDate datetime,
@EndDate datetime
AS
BEGIN
select * from abc where date between @startdate and @enddate;
go;
select * from xyz where date <@enddate;
go;
select * from def where date > @startdate;
go;
END
And you use a SqlDataAdapter to fill a DataSet
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.