带有IF的MSSQL WHERE

时间:2016-06-08 06:56:00

标签: sql-server if-statement where

我正在尝试进行以下操作的查询:

<!DOCTYPE html>
<html>
<head><title></title>

</head>
<body>
	<svg height="210" width="500">
	<line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" />
	<line x1="150" y1="150" x2="200" y2="200" style="stroke:rgb(0, 0, 153);stroke-width:2">
		<animateTransform attributeName="transform"
      type="translate"
      from="200 200"
      to="-150 -150"
      begin="0s"
      dur="5s"
      repeatCount="indefinite"
    />
	</line>
	</svg>


	
</body>
</html>

我在if子句中的If条件中唯一可以找到的是CASES。我无法找到允许多个条件的案例。

到目前为止,我必须通过在SELECT语句之外使用If并复制语句但更改WHERE子句来实现此目的。

2 个答案:

答案 0 :(得分:6)

SELECT * FROM Test
WHERE
(Condition = True
    AND Column1 = 'This'
    AND Column2 = 'That')
OR
(Condition = FALSE
    AND Column3 = 'This'
    AND column4 = 'That')

答案 1 :(得分:1)

您可以使用PROCEDUREFUNCTION来执行此操作。

例如使用PROCEDURE:

CREATE PROCEDURE test (IN _condition BOOLEAN, IN _this VARCHAR(255), IN _that VARCHAR(255))
BEGIN
    IF _condition THEN
        SELECT * FROM Test WHERE Column1 = _this AND Column2 = _that;
    ELSE
        SELECT * FROM Test WHERE Column3 = _this AND Column4 = _that;
    END IF;
END;

要运行此功能,请执行CALL test(TRUE, 'This', 'That')

您可以将 _ condition 替换为您自己的条件,例如:

CREATE PROCEDURE test1 (IN _number INT(11), IN _this VARCHAR(255), IN _that VARCHAR(255))
BEGIN
    IF _number >= 2016 THEN
        SELECT * FROM Test WHERE Column1 = _this AND Column2 = _that;
    ELSE
        SELECT * FROM Test WHERE Column3 = _this AND Column4 = _that;
    END IF;
END;

执行CALL test1(2015, 'This', 'That')