Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored Procedure with variable condition and error message

In my procedure, the variable @year should take two forms: 1: If @Year=1, Select all years. 2: @Year= the entered year.

Here's a sample of my code:

CREATE PROC spProcName (@Year)
AS
BEGIN 
SELECT Year AS [YEAR], Item AS [ITEM]
FROM Sales
WHERE Year = @YEAR

I can make it work for @Year = 2013, but I don't know how to incorporate the @Year =1 to select all years. I'm guessing it would be with CASE.

I also have many other similar conditions with other variables, so I can't just create an IF statement.

like image 827
user107242 Avatar asked Jan 18 '26 15:01

user107242


1 Answers

Where Year = Case when @Year = 1 Then Year else @Year end
like image 75
John Cappelletti Avatar answered Jan 20 '26 04:01

John Cappelletti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!