2014-08-30 94 views
0

我的表是這樣的:如何寫SQL Server存儲過程

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 

我怎麼能在一個單一的選擇查詢管理呢?

回答

2

你可以試試這個:

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

感謝Farrokh。有用 – 2014-08-30 09:06:35