Stored Procedure with variable condition and error message

时间:2016-10-20 19:05:15

标签: sql sql-server tsql stored-procedures

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.

3 个答案:

答案 0 :(得分:6)

Where Year = Case when @Year = 1 Then Year else @Year end

答案 1 :(得分:6)

Alternative to John's answer, but quasi-equivalent:

WHERE (@year=1 OR year=@year)

In this case it is best to add OPTION(RECOMPILE) at the end of the query, otherwise the query won't be able to choose an index if it exists on the year column.

答案 2 :(得分:0)

--If you give value 1 it will select all the records from table year wise else if you give year like 2016 it fetches all the record based on given year
ALTER PROC spProcName (@Year int)
AS
BEGIN
  IF @Year = 1
  BEGIN
    SELECT
      [Year] AS [YEAR],
      Item AS [ITEM]
    FROM Sales
        ORDER BY [Year]
  END
  ELSE
    SELECT
      [Year] AS [YEAR],
      Item AS [ITEM]
    FROM Sales
        WHERE DATEPART(YEAR, CAST([Year] AS date)) = @year
END