SQL可以在select过程中放置​​if语句吗?

时间:2013-02-22 15:49:18

标签: sql stored-procedures if-statement procedure

我需要在我的程序中添加一个if语句,类似这样的

CREATE PROCEDURE [dbo].[myProcedure]
  @name VARCHAR(8000) = NULL
 ,@lname VARCHAR(8000) = NULL
 ,@flag CHAR(1) = NULL


AS
BEGIN
 SET NOCOUNT ON;
    WITH t 
    (name
    ,lname
    )

AS
(
    SELECT DISTINCT 
    * FROM mytable
    WHERE 
  (@name IS NULL OR @name = name)
   IF @flag = 'c'
   BEGIN
      AND (@lname IS NULL OR @lname = 'Doe')
   END
   ELSE 
   BEGIN
    AND (@lname IS NULL OR @lname = lname)
   END
)

正如您所看到的,根据标志,我以某种方式使用lname字段。 我在if部分遇到错误..是不是我在这里不能使用if语句? 如果没有,我该如何替换if语句?

非常感谢

3 个答案:

答案 0 :(得分:2)

你可以这样做:

SELECT DISTINCT * 
FROM mytable
WHERE 
  (@name IS NULL OR @name = name)
   AND 
   (
      (@flag = 'c' AND (@lname IS NULL OR @lname = 'Doe'))
      OR 
      (@flag != 'c' AND (@lname IS NULL OR @lname = lname))
   )

答案 1 :(得分:0)

只是提供一个替代答案(因为我认为CASE语句是SQL中IF语句的真实模拟):

SELECT 
DISTINCT 
    * 
FROM 
    mytable
WHERE 
    (@name IS NULL OR @name = name)
    AND 
    (@lname is NULL OR @lname = 
    CASE 
        WHEN @flag ='c' THEN 'Doe'
        ELSE lname
    END
    )

答案 2 :(得分:0)

试试这个

....
WHERE 
(@name IS NULL OR @name = name) AND
(
   (@flag = 'c' AND (@lname IS NULL OR @lname = 'Doe')) OR
   (@lname IS NULL OR @lname = lname)
)