Combine results from multiple stored procedures - sql

I have 3 stored procedures (spData1, spData2, spData3) that query regional summary results from two tables (tSites, tInspections) linked by a SiteID key. I cannot combine the queries due to differing join methods and GROUP BY requirements of the required summary information. Each stored procedure takes a #Year (smallint) parameter for the year in which they want the summary information. And to makes things really fun, the procedures don't always return the same number of records, depending on the year.
spData1 returns RegionName, TotalSitesVisited, and TotalViolations
spData2 returns RegionName and TotalSiteVisits
spData3 returns RegionName and TotalBadSites
How do I create a fourth stored procedure to return all of this information in one result:
spData4 returns RegionName, TotalSitesVisited, TotalViolations, TotalSiteVisits, TotalBadSites
Thanks!

At the beginning of your procedure (spData4) create three temp tables that corespond to the output columns of three stored procedures.
Run all 3 sps using INSERT..EXEC and insert data into 3 temp tables.
At the end write a query that JOIN the result of 3 temp tables and return it as SELECT from procedure
Something like this (fix for your correct column types):
CREATE PROCEDURE spData4 (#Year smallint)
AS
BEGIN
CREATE TABLE #temp1 (RegionName NVARCHAR(50), TotalSitesVisited INT, TotalViolations INT)
CREATE TABLE #temp2 (RegionName NVARCHAR(50), TotalSiteVisits INT)
CREATE TABLE #temp3 (RegionName NVARCHAR(50), TotalBadSites INT)
INSERT INTO #temp1 EXEC spData1 #Year
INSERT INTO #temp2 EXEC spData2 #Year
INSERT INTO #temp3 EXEC spData3 #Year
SELECT
COALESCE(t1.RegionName, t2.RegionName, t3.RegionName) RegionName
,TotalSitesVisited,TotalViolations,TotalSiteVisits,TotalBadSites
FROM #temp1 t1
FULL JOIN #temp2 t2 ON t1.RegionName = t2.RegionName
FULL JOIN #temp3 t3 ON t1.RegionName = t3.RegionName OR t2.RegionName = t3.RegionName
END
Alternatively, if you don't need old SPs anymore, you can copy your code from all three SPs here and have it as three separate parts that each fill it's own #temp table. Join at the end the same way.

Related

Need to log identifiers from select query recordset along with date/time stamp

I would like to log all records generated by a sql select statement in an SSRS report into a table for later reference at the time the report is run.
One idea is to append the unique ID to the reference table and then perform the full query with the additional data for the full record set, but i feel like there is probably a better way.
One way would be to use a STORED PROCEDURE for your SSRS report instead of hard coding the query in the RDL. Then, you could leverage the OUTPUT clause and log the query execution, and return the results. The proc would look something like this:
create procedure myProc (#param1 int)
as
begin
declare #resultTable table (id int, c1 char(4), c2 char(4))
insert into myloggingtable
output INSERTED.id, INSERTED.c2, INSERTED.c3 into #resultTable
select
id,
c1,
c2,
RunDateTime = getdate(),
from SomeTable
where id = #param1
select * from #resultTable
end
Here, I would have an auto-incremented key on the myloggingtable and the RunDateTime would be logged as the execution time.

SQL Server stored procedure - delete rows based on multiple parameters

I need help figuring out how to build a stored procedure that will delete rows based on two parameters.
Assume I have two identical tables, Table1 and Table2 both containing columns Date, Name, and Number. I want to delete rows from Table1 based on Date and Name, and Insert Into Table1 From Table2.
Essentially I want it to function somewhere along the lines of:
Delete From Table1
Where (Table1.Date = Table2.Date) AND (Table1.Name = Table2.Name)
and then:
Insert Into Table1
Select * From Table2
I'm not familiar with how stored procedures work so I greatly appreciate the help.
Query for creating this kind of procedure goes like this:
CREATE PROCEDURE DummyProc
#Date DATE,
#Name VARCHAR(20) --Or NVARCHAR if you have UNICODE data
AS
BEGIN
DELETE FROM Table_1
WHERE Table_1.Date = #Date AND Table_1.Name= #Name
INSERT INTO Table_1
SELECT Date, Name, Number --You can specify columns
FROM Table_2
END
GO
And for executing with query:
EXEC dbo.DummyProc 'enter Date here', 'enter Name here';
GO

Present Data in Presentation Layer after Removing the Temp Table

Inside of stored procedure you have the code
create table #datatable (id int,
name varchar(100),
email varchar(10),
phone varchar(10),
cellphone varchar(10),
none varchar(10)
);
insert into #datatable
exec ('select *
from datatable
where id = 1')
select * from #datatable
I still want to retrieve the data and present it in the software's presentation layer but I still want to remove the temp table in order to reduce performance issue etc.
If I paste the code DROP TABLE #datatable after
insert into #datatable
exec ('select *
from datatable
where id = 1')
Does it gonna work to present the data in the presentation layer after removing the temp table?
Thanks!
http://sqlfiddle.com/#!3/14bbc/1/1
Just drop the table after select .becoz it no use to drop table without showing output from temp table used inside the SP
create table #datatable (id int,
name varchar(100),
email varchar(10),
phone varchar(10),
cellphone varchar(10),
none varchar(10)
);
insert into #datatable
exec ('select *
from datatable
where id = 1')
select * from #datatable
drop table #datatable
EDIT: You say you have a reason for doing it so ignore my answer below. Answering whether you can drop the temp table then yes you can, and your data will still be returned by your stored procedure. You can just put the
DROP TABLE #datatable
line in after your
select * from #datatable
line and you'll be fine. It's good practice to clean up after yourself, even though your temp table will only have a lifetime of the current user session.
Also, in one of your comments you say "I want to remove the data temp because the this SP will be used many time." Local temporary tables are not accessible by other users, and their data does not persist between user sessions, so no other call to this stored procedure would access the information from the temp table that is created within the first call.
Initial Answer:
I don't see why you are using a temporary table at all here? Unless you are doing other processing than what is in your fiddle etc then why can't you just use a simple select? There is no need to use a temporary table or EXEC a select into it for this case. Obviously you may have just simplified your question in that case just ignore this answer but if not then your SP would just be
CREATE PROCEDURE [procname]
(
#id int
)
AS
BEGIN
SELECT id
name,
email,
phone,
cellphone,
none
FROM datatable
WHERE id = #id
END
If you type the drop table after the insert statement you won't be able to get any result from the subsequent select: you dropped a table and SQL will say it doesn't know the table you are asking for. Get the data and then drop the table

How to insert data into a vertically partitioned table in sql server

I have a problem with the partitioning of a table in the SQL Server. I have a table with over 103 columns out of which only 20 are used very frequently and are referenced by a number of tables.
As the table contains thousands of rows I have created a vertical partition and divided the table into multiple tables so as to save the table data in different file groups.
I have also created a view by joining those tables. And now, how do i insert data into different tables without using INSTEAD OF triggers?
You can use stored procedure to encapsulate all your insert logic.
If you have, let's say, 3 tables that share same ID column and each have it additional columns, your stored procedure might look something like this:
CREATE PROCEDURE usp_Insert
(
#Val1 VARCHAR(5)
, #Val2 VARCHAR(5)
, #Val3 VARCHAR(5)
)
AS
BEGIN
DECLARE #id INT;
INSERT INTO Table1 (Col1) VALUES (#Val1);
SELECT #id = SCOPE_IDENTITY();
INSERT INTO Table2 (ID, Col2) VALUES (#id, #Val2);
INSERT INTO Table3 (ID, Col3) VALUES (#id, #Val3);
END
GO
SQLFiddle Working demo and sample tables

Insert into Table select result set from stored procedure but column count is not same

I need something like that which is of course not working.
insert into Table1
(
Id,
Value
)
select Id, value from
(
exec MySPReturning10Columns
)
I wanted to populate Table1 from result set returned by MySPReturning10Columns. Here the SP is returning 10 columns and the table has just 2 columns.
The following way works as long as table and result set from SP have same number of columns but in my case they are not same.
INSERT INTO TableWith2Columns
EXEC usp_MySPReturning2Columns;
Also, I want to avoid adding "." as linked server just to make openquery and openrowset work anyhow.
Is there a way not to have define table strucutre in temp table (all columns with datatypes and lenght)? Something like CTE.
You could use a temporary table as a go-between:
insert into #TempTable exec MySP
insert into Table1 (id, value) select id, value from #TempTable
You could solve the problem in two steps by doing the insert from the stored procedure into a temporary table, then do the insert selecting just the columns you want from the temporary table.
Information on temporary tables: http://www.sqlteam.com/article/temporary-tables
-- Well, declare a temp table or a table var, depending on the number of rows expected
-- from the SP. This table will be basically the result set of your SP.
DECLARE #spResult AS TABLE
(
ID INT,
VALUE FLOAT,
....
);
-- Get the result set of the SP into the temp table.
INSERT #spResult EXEC STORED_PROC;
-- Now you can query the SP's result set for ID and Value;
INSERT Table1 (ID, VALUE)
SELECT ID, VALUE FROM #spResult;
You dont need to create a temporary table, you can do it with single query by creating temporary view like this
with tempView as EXEC MySPReturning10Columns insert into Table1 select id, value from tempView
The temporary view disappears as soon as the statement finishes execution