SQL Server存储过程WHERE子句

时间:2014-01-06 21:18:11

标签: sql sql-server stored-procedures parameter-passing where-clause

在此存储过程中需要WHERE子句的帮助。

如何使用此参数编写WHERE,如果这些参数中的任何一个包含特定值,那么我需要从该列获取所有值吗?

如果@post1包含1,则为示例,然后从该列中选择等于1的值。 但是,如果@post1包含0,则选择该列中的所有值。对于所有其他参数。

ALTER PROCEDURE [dbo].[spStavke] 
    @dat1 date,
    @dat2 date,
    @god int, 
    @post1 int,
    @post2 int,
    @post3 int
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 
       [test1]
      ,[test2]
      ,[test3]
      ,[test3]
    FROM 
      [PN].[dbo].[Stavke] AS stavke
    LEFT JOIN 
      PN.dbo.Tip AS tip ON stavke.Vrsta = tip.id
    LEFT JOIN
      PN.dbo.Vrsta AS vrs ON stavke.Jedinica = vrs.id
END

1 个答案:

答案 0 :(得分:2)

SELECT 
      [test1]
     ,[test2]
     ,[test3]
     ,[test3]

FROM [PN].[dbo].[Stavke] as  stavke
left join PN.dbo.Tip  as tip on  stavke.Vrsta=tip.id
left join PN.dbo.Vrsta  as vrs on  stavke.Jedinica = vrs.id
WHERE (@Post1 = 0 OR (@Post1 = 1 AND 1 IN( TEST1,TEST2,TEST3))
 AND (@Post2 = 0 OR (@Post2 = 1 AND 1 IN( TEST1,TEST2,TEST3))