简体   繁体   中英

SSMS - Varying number of parameters in a stored procedure

I have an issue regarding the number of parameters I put in a stored procedure. I'm automating a report with quarterly data (parameter format = 2012Q1, 2012Q2, and so on).
If the user's first parameter starts with Q1, Q2, or Q3, there will only be 3 years of data so if the user's first parameter is 2012Q1, 2012Q2, or 2012Q3, the parameters will end at 2014Q4....the number of parameters will be different since it requires 12 parameters from 2012Q1-2012Q4, 11 parameters from 2012Q2-2014Q4, and 10 parameters from 2012Q3-2014Q4.

Is it possible to change the number of parameters declared based on what the user's first parameter is like??? Is there even a good way to tackle this?

No this is not possible, however you can have the parameters have a default value of NULL, now it is not required to pass a value in.

example

create procedure prTest 
@i int = null, @i2 int = null
as
select @i,@i2
go

exec prTest 1  --just pass 1 parameter, 2nd is default
go
exec prTest   -- leave all as default
go
exec prTest @i2 = 5  --to pass in a param if it is not 1st, use names
go
exec prTest null,5  --same as above

See also: Optional and named arguments in C# a comparison with SQL Server stored procs

Instead of doing this why don't you just use start and end date or can they choose quarters from multiple years ad hoc?

I think you can simplify things immensely by just having two parameters. The first one will specify the start of your search period and the second one will specify the end. Whether these are dates, year-months, or names of periods is something you can figure out,

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM