Sql 具有可变条件和错误消息的存储过程
在我的过程中,变量@year应该采用两种形式:1:如果@year=1,选择所有年份。2:@Year=输入的年份 以下是我的代码示例:Sql 具有可变条件和错误消息的存储过程,sql,sql-server,tsql,stored-procedures,Sql,Sql Server,Tsql,Stored Procedures,在我的过程中,变量@year应该采用两种形式:1:如果@year=1,选择所有年份。2:@Year=输入的年份 以下是我的代码示例: CREATE PROC spProcName (@Year) AS BEGIN SELECT Year AS [YEAR], Item AS [ITEM] FROM Sales WHERE Year = @YEAR 我可以让它在@Year=2013年运行,但我不知道如何合并@Year=1来选择所有年份。我猜是凯斯 我还有许多其他类似的条件和其他变量,所以我不能
CREATE PROC spProcName (@Year)
AS
BEGIN
SELECT Year AS [YEAR], Item AS [ITEM]
FROM Sales
WHERE Year = @YEAR
我可以让它在@Year=2013年运行,但我不知道如何合并@Year=1来选择所有年份。我猜是凯斯
我还有许多其他类似的条件和其他变量,所以我不能只创建一个IF语句 约翰答案的替代方案,但准等效:
Where Year = Case when @Year = 1 Then Year else @Year end
WHERE (@year=1 OR year=@year)
在这种情况下,最好在查询结束时添加
选项(重新编译)
,否则,如果年份
列中存在索引,则查询将无法选择索引。@user107242乐意提供帮助。
--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