0

我需要在我的过程中添加一个 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 语句?

非常感谢

4

3 回答 3

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))
   )
于 2013-02-22T15:51:58.040 回答
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
    )
于 2013-02-22T15:56:23.190 回答
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)
)
于 2013-02-22T15:57:53.450 回答