T-SQL中的AND与OR

时间:2019-01-22 19:50:11

标签: sql sql-server

几年后,我将重新使用T-SQL。我正在尝试执行如下所示的SQL查询,但似乎OR子句使它忽略了AND。

是否可以获取syscolumns.name包含'sp'或'tbl'但XTYPE不是P的对象?

我尝试使用括号,但是SQL Server似乎不喜欢它们。

use master

SELECT 
    c.name AS columnname, o.name AS tablename, o.xtype
FROM 
    syscolumns c 
JOIN 
    sysobjects o ON c.id = o.id
WHERE 
    UPPER(c.name) LIKE UPPER('%sp%') 
    OR UPPER(c.name) LIKE UPPER('%tbl%') 
    AND o.xtype NOT LIKE ('P%')
ORDER BY 
    tablename DESC

2 个答案:

答案 0 :(得分:3)

AND的优先级高于OR。您首先需要添加括号以计算OR,如下所示:

SELECT c.name AS columnname, o.name AS tablename, o.xtype
FROM syscolumns c 
JOIN sysobjects o ON c.id = o.id
WHERE 
( -- added parenthesis
upper(c.name) LIKE UPPER('%sp%') 
OR upper(c.name) LIKE UPPER('%tbl%') 
) -- added parenthesis
AND o.xtype NOT LIKE ('P%')
ORDER BY tablename desc

答案 1 :(得分:1)

这有效,我只是在where子句中添加了括号。

use master
SELECT c.name AS columnname, o.name AS tablename, o.xtype
FROM syscolumns c 
JOIN sysobjects o ON c.id = o.id
WHERE 
(upper(c.name) LIKE UPPER('%sp%') OR upper(c.name) LIKE UPPER('%tbl%') )
AND o.xtype NOT LIKE ('P%')
ORDER BY tablename desc