如何在SQL Server中编写存储过程

时间:2014-08-30 08:12:34

标签: sql sql-server-2008

我有这样的表:

CREATE TABLE [dbo].[tblSingleQuery]
(
    Id Int IDENTITY(1,1),
    ProdId INT,
    ColorId INT,
    IsFront BIT DEFAULT 0
)

enter image description here

我想创建一个带有输入参数@ColorId的存储过程,它将使用where子句ColorId <> @ColorId获取结果。但是当我通过@ColorId = 0时,它应该排除IsFront = 1的记录。

目前我已经创建了这样的存储过程:

CREATE PROCEDURE [dbo].[proc_GetProductColorImage]
    @ColorId INT
AS
BEGIN
   IF @ColorId = 0
   BEGIN
       SELECT * 
       FROM [tblSingleQuery] 
       WHERE IsFront <> 1
   END
   ELSE
   BEGIN
       SELECT * 
       FROM [tblSingleQuery] 
       WHERE ColorId <> @ColorId 
   END
END

如何在单个选择查询中管理此内容?

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

SELECT * 
FROM [tblSingleQuery] 
WHERE
    (@ColorId = 0 AND IsFront <> 1 ) OR 
    (@ColorId != 0 AND ColorId <> @ColorId )