在MySQL中具有多个SELECT的IF语句

时间:2012-10-08 12:04:19

标签: c# mysql

我在Visual Studio 2010 C#语言中使用MySQL。

我需要进行查询。

SELECT a field, if this field is null or equals to 0

制作另一个SELECT,如果它与<>null不同0。 再做一次SELECT

我也尝试按照上面写的标题时出现的建议,但没有。

喜欢的东西:

SELECT cart.cod_dependent (if cart.cod_dependent <> 0, Select ass.matricula, ass.nome, ass.situacao_social, ass.categoria, ELSE IF cart.cod_dependent = null Make another select)

每个选择将在不同的表中,但都在同一个数据库中。

------更新10/08/2012 09:59 -------- 现在我正在尝试你所说的 Radu Bompa ,但它说“在执行命令期间遇到致命错误”= \。

 MySqlCommand cmd = new MySqlCommand();
  string sql = @"SELECT @cod_dep = cart.cod_dependente FROM carteiras as cart
  IF @cod_dep IS NULL
  BEGIN
  SELECT ass.matricula, ass.nome, ass.situacao_social, ass.categoria FROM associados AS ass INNER JOIN categorias AS cat ON cat.codigo = ass.categoria,
  INNER JOIN situacoes_social AS ss ON ass.situacao_social = ss.codigo
  END
  ELSE
  BEGIN
  SELECT dep.nome, dep.matricula, dep.situacao_social, ss.descricao FROM dependentes INNER JOIN situacao_social as ss dep.situacao_social = ss.codigo
  END
  WHERE cart.numero = @carteira";
  cmd.CommandText = sql;
  cmd.CommandType = CommandType.Text;
  string dependente = "";
  cmd.Parameters.Add(new MySqlParameter("@carteira", MySqlDbType.Int32)).Value = carteira;
  DataSet ds = _dal.Consultar(cmd);

1 个答案:

答案 0 :(得分:0)

也许这样的事情可行:

SELECT @SomeValue = cart.cod_dependent FROM cart   
--@SomeValue is a variable, declared for this purpose
IF @SomeValue IS NULL
BEGIN
  SELECT ass.matricula, ass.nome, ass.situacao_social, ass.categoria FROM table2
END
ELSE
BEGIN
  SELECT field FROM table3
END

您也可以尝试使用stored procedure