如何在带有where子句的sql server中使用if else

时间:2014-03-24 07:46:44

标签: sql

CREATE PROCEDURE findlist @comedianname1 nvarchar(30),@comedianname2 nvarchar(30)
AS
SELECT comedian 
FROM Comedian
if @comedianname2!=null
begin
WHERE comedian! = @comedianname1 and comedian! = @comedianname2
end
else
begin
WHERE comedian! = @comedianname1
end
GO

我收到此错误:消息156,级别15,状态1,程序搜索列表,第7行 关键字'WHERE'附近的语法不正确。

3 个答案:

答案 0 :(得分:3)

您无法在选择中使用IF。你可以在你的情况下这样做:

SELECT comedian 
FROM Comedian
WHERE
    comedian! = @comedianname1 AND
    comedian! = ISNULL(@comedianname2, comedian!)

它做什么?如果将comedian!@comedianname1进行比较,如果@comedianname2不为空,则会将comedian!@comedianname2进行比较。否则,它会将comedian!comedian!进行比较,true始终为{{1}}。

答案 1 :(得分:2)

您需要使用以下查询

SELECT comedian 
FROM Comedian
WHERE comedian! = @comedianname1 and (comedian! = @comedianname2 OR @comedianname2 IS NULL)

答案 2 :(得分:1)

试试这个

CREATE PROCEDURE findlist @comedianname1 nvarchar(30),@comedianname2 nvarchar(30)
AS
  SELECT comedian 
  FROM Comedian
  WHERE (comedian! = @comedianname1 and comedian! = @comedianname2) OR (comedian! = @comedianname1)
GO