我正在尝试编写一个存储过程,该过程将有6位值标志作为参数和其他几个值。
我想写的伪sql是这样的:
SELECT *
FROM theTable
WHERE
IF @flagA = 1 THEN theTable.A = 1
IF @flagB = 1 THEN theTable.B = 1
IF @flagC = 1 THEN theTable.CValue = @cValue
etc
我有什么想法可以在SQL中执行此操作,或者我最好还是在C#中构建SQL(将从哪里调用此SP)?
答案 0 :(得分:5)
SELECT *
FROM theTable
WHERE
(@flagA = 0 or (@flagA = 1 AND theTable.A = 1 ))
and (@flagB = 0 or (@flagB = 1 AND theTable.B = 1 ))
and (@flagC = 0 or (@flagC = 1 AND theTable.CValue = @cValue ))
注意:我假设你的位标志是不可为空的。如果不是这种情况,则需要使用ISNULL
。