在sqlite中替换以下查询

时间:2015-06-17 04:09:44

标签: c# sql-server if-statement sqlite

我在带有参数@firstId和@secondId

的商店过程中有如下sql server查询
IF @firstId = ''
begin

SELECT DISTINCT x, y =
FROM t1
LEFT OUTER JOIN t2 ON t1.id = t2.id AND t2.id = @secondId
ORDER BY t1.somecolumn

END
ELSE
BEGIN

SELECT DISTINCT x, y =
FROM t1
LEFT OUTER JOIN t2 ON t1.id = t2.id AND t2.id = @secondId
AND t1.id = @firstId
ORDER BY t1.somecolumn
END

我对sqlite很新,并尝试在sqlite中使用case语句编写上述查询,如sqlite文档中所建议的那样,但到目前为止还无法实现相同的目的。我希望实现类似下面的内容或更好的查询。

CASE WHEN @firstId = '' THEN (CHOOSE FIRST SELECT STATEMENT) ELSE (CHOOSE SECOND SELECT STATEMENT) END

我想把原始的sql查询拆分成sqlite中的两个select语句,并根据c#代码库文件中处理的条件调用相应的查询,如下所示,但不确定这是不是很好。

if(firstId == string.empty)
{
//call the first select statement
}
else
{
//call the second select statement
}

我不想将商店流程拆分为两个单独的查询。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

你可以一气呵成。以上2个陈述相当于:

SELECT DISTINCT x, y
FROM t1
LEFT OUTER JOIN t2 ON t1.id = t2.id AND t2.id = @secondId
                      AND (t1.id = @firstId OR  @firstId = '')
ORDER BY t1.somecolumn