Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common Table Expression, why semicolon?

Usually in SQL Server Common Table Expression clause there is semicolon in front of the statement, like this:

;WITH OrderedOrders AS --semicolon here (     SELECT SalesOrderID, OrderDate,     ROW_NUMBER() OVER (ORDER BY OrderDate) AS 'RowNumber'     FROM Sales.SalesOrderHeader  )  SELECT *  FROM OrderedOrders  WHERE RowNumber BETWEEN 50 AND 60 

Why?

like image 459
jrara Avatar asked Aug 04 '11 08:08

jrara


People also ask

Why do we use semicolon in SQL statements?

Some database systems require a semicolon at the end of each SQL statement. Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server.

Is semicolon mandatory in mysql?

If you're writing single statements in, say, PHP and then sending them to MySQL for processing, the semicolon is optional. You ask if it "might have possible negative effects maybe during server high load, caching etc." The answer to that is 'No'.

Is it mandatory to enclose every SQL query with semicolon at the end of pick one option True False?

The semicolon (;) is used in SQL code as a statement terminator. For most SQL Server T-SQL statements it is not mandatory.

Why would you use a common table expression?

CTEs, like database views and derived tables, enable users to more easily write and maintain complex queries via increased readability and simplification. This reduction in complexity is achieved by deconstructing ordinarily complex queries into simple blocks to be used, and reused if necessary, in rewriting the query.


1 Answers

  • To avoid ambiguity because WITH can be used elsewhere
    ..FROM..WITH (NOLOCK)..
    RESTORE..WITH MOVE..
  • It's optional to terminate statements with ; in SQL Server

Put together, the previous statement must be terminated before a WITH/CTE. To avoid errors, most folk use ;WITH because we don't know what is before the CTE

So

DECLARE @foo int;  WITH OrderedOrders AS (     SELECT SalesOrderID, OrderDate, ...; 

is the same as

DECLARE @foo int  ;WITH OrderedOrders AS (     SELECT SalesOrderID, OrderDate, ...; 

The MERGE command has a similar requirement.

like image 62
gbn Avatar answered Sep 28 '22 04:09

gbn