SQL服务器,使用or语句条件

SQL Server, using or statement condition

我正在使用一个查询,它在 table 中搜索两个条件。我举个例子:

Select * 
from Customers 
where mobile= '" + textboxt1.Text + "' or Phone = '" + textboxt1.Text + "' 

查询returns我第一行哪个手机或phone号码与我的textbox1.Text相等。

我需要设置一个条件:开始查找 "entire table" 以找到第一个 'or' 语句(移动)。如果不存在任何结果,则使用第二个或条件 (Phone).

再次搜索整个 table

有什么简单的方法可以编写我的查询吗?或者我需要为此使用案例吗?

假设 table 中不超过一条记录与 mobile 匹配,并且不超过一条记录与 phone 匹配(考虑到您的您的用例描述),您可以使用 top 1 和条件排序:

select top 1 * 
from Customers 
where mobile= @textboxt1 or phone = @textboxt2
order by case when mobile= @textboxt1 then 0 else 1 end

如果一条记录在 mobile 上匹配,条件排序子句会将其放在第一位,而 top 1 将消除在 phone 上匹配的(可能的)其他记录。否则,将保留 phone 上的(唯一)匹配记录。

注意:不要相信用户输入。始终使用 prepared statement and query parameters。我修改了查询,因此它使用参数 (@textboxt1, @textboxt2).

您有时可以通过选择 UNION 而不是 OR 来提高性能。

SELECT TOP 1 * FROM (
    SELECT *, 0 Ordinal
    FROM Customers
    WHERE mobile = @number

    UNION ALL

    SELECT *, 1 Ordinal
    FROM Customers
    WHERE phone = @number  
) t
ORDER BY Ordinal