There are times when it is really convenient to gather data in a view and then use that view in one or more stored procs to build a complex dataset. Sometimes, however, that base dataset can run much more efficiently if you use one or more temp tables to join data. Views can;t handle this type of logic, but stored procs can. Historically, it was difficult to use the dataset returned rom a stored proc in the logic of other stored procs, but nowadays it is relatively easy using temp table variables.
Say we have a stored proc that returns a dataset like this:
create proc myBaseData(
@param1 int,
@param2 datetime
)
as
begin
select @param1 as int1,
@param2 as date1
end
go
Now say we want to call that proc and use the dataset in another proc, but we don;t want to save the records to a physical table. We can insert the proc results in a table variable like so:
create proc MyCallingProc(
@param1 int
)
as
begin
declare @mytable as table(
col1 int,
col2 datetime
)
declare @d datetime
select @d=convert(varchar,GETDATE(),112)
insert into @mytable
exec myBaseData @param1,@d
select * from @mytable
end
go
We can then execute it as follows:
exec MyCallingProc 1
The big bonus here is that I don;t have to create a view and take the performance hit of filtering it every time I join it. The params on the proc can be used to filter the results before joining.
Another bonus is that I can set a primary key (unique index) on the table variable, which is something I can't do in the view.
Did this help you? If so, please leave a comment!
David Jedziniak maintains this blog and posts helpful tips and tricks on SQL Server and Dynamics GP development. The opinions expressed here are those of the author and do not represent the views, express or implied, of any past or present employer. The information here is provided without warranty of fitness for any particular purpose.
Subscribe to:
Posts (Atom)
SQL 2022 TSQL snapshot backups!
SQL 2022 now actually supports snapshot backups! More specifically, T-SQL snapshot backups. Of course this is hardware-dependent. Here ...
-
If you are reading this, you are probably aware of the fact that you cannot deploy SSRS 2008 reports on an SSRS2005 server. SSRS reports ar...
-
SQL Job to refresh TEST from PRODUCTION Last Updated: 2018.11.12 I like to include each of these steps as a separate job step. If you ...
-
I ran into an issue today where I had a report parameter default that I couldn't seem to get rid of. In BIDS, I deleted the defaults f...