如果语法错误,SQL Exists语句如何工作?

前端之家收集整理的这篇文章主要介绍了如果语法错误,SQL Exists语句如何工作?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么SQL查询工作,即使SELECT缺少一个FROM,这将是一个语法错误.另请注意,查询显示满足WHERE子句的查询.
CREATE TABLE Customer_Tbl
(
    CustomerName VARCHAR(50),Address VARCHAR(250),Country VARCHAR(50)
);


INSERT INTO Customer_Tbl 
VALUES
    ('AAA','','Philippines'),('BBB','Mexico'),('CCC',('DDD',('EEE','Philippines');


SELECT *
FROM Customer_Tbl 
WHERE EXISTS(
    -- This is missing a FROM
    -- running it by itself is a Syntax error.
    SELECT 2 Customer_Tbl 
    WHERE Country = 'MEXICO'
);

这是对sql Server 2012和2014的测试,这里有一个在线示例:http://rextester.com/GDGB80815

解决方法

sql Server在SELECT语句中不要求FROM.

例如,以下查询中没有语法错误

SELECT 2 AS t
WHERE 0 = 0

它返回一行,列为t和值2.

你可以写简单

SELECT 2 AS t

得到相同的结果.

您的查询与此相同:

SELECT *
FROM Customer_Tbl 
WHERE EXISTS(
    SELECT 2 AS Customer_Tbl 
    WHERE Customer_Tbl.Country = 'MEXICO'
);

Inner Customer_Tbl是具有常量2的列的别名.WHERE中的国家是外部表Customer_Tbl的列.

使用AS进行别名是一个很好的做法,并用列表完全限定列.

当您尝试分开运行内部零件时

SELECT 2 Customer_Tbl 
WHERE Country = 'MEXICO'

它不是因为没有FROM,而是因为解析器不知道是什么国家:

Msg 207,Level 16,State 1,Line 2 Invalid column name ‘Country’.

为了完整起见,这里是sql Server从MSDN开始的SELECT语句的语法:

<SELECT statement> ::=    
    [ WITH { [ XMLNAMESPACES,] [ <common_table_expression> [,...n] ] } ]  
    <query_expression>   
    [ ORDER BY { order_by_expression | column_position [ ASC | DESC ] }   
  [,...n ] ]   
    [ <FOR Clause>]   
    [ OPTION ( <query_hint> [,...n ] ) ]   
<query_expression> ::=   
    { <query_specification> | ( <query_expression> ) }   
    [  { UNION [ ALL ] | EXCEPT | INTERSECT }  
        <query_specification> | ( <query_expression> ) [...n ] ]   
<query_specification> ::=   
SELECT [ ALL | DISTINCT ]   
    [TOP ( expression ) [PERCENT] [ WITH TIES ] ]   
    < select_list >   
    [ INTO new_table ]   
    [ FROM { <table_source> } [,...n ] ]   
    [ WHERE <search_condition> ]   
    [ <GROUP BY> ]   
    [ HAVING < search_condition > ]

可选子句用方括号[]表示.如你所见,几乎所有的子句都是可选的,包括FROM,除了SELECT关键字本身和< select_list&gt ;.

猜你在找的MsSQL相关文章