Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Folks!!

I have a doubt on CTE..If we are using CTE inside SP..Previous statement must be terminated with Semicolon(;)..Why??

declare @date varchar(10)
set @date=GETDATE();

WITH CTEQuery AS (
SELECT CAST('23 Mar 2014' AS DATETIME) AS dt
UNION ALL
SELECT DATEADD(dd, 1, dt)
FROM CTEQuery s
WHERE DATEADD(dd, 1, dt) <= CAST('26 Jun 2014' AS DATETIME)
)
select * from CTEQuery


Thanks in Advance!!

What I have tried:

I don't know the reason why Semicolon is required .I just want to know the Reason .
Posted
Updated 11-Mar-16 0:37am
Comments
jaket-cp 11-Mar-16 7:17am    
On a side note: possibly get in the habit of using the semicolon statement terminator for all statements.

"Not ending Transact-SQL statements with a semicolon" has been put in the list of
Features Not Supported in a Future Version of SQL Server
https://msdn.microsoft.com/en-us/library/ms143729(v=sql.120).aspx

Not saying it is going to happen any time soon though.

1 solution

That is by design:
Quote:
When a CTE is used in a statement that is part of a batch, the statement before it must be followed by a semicolon.

You must read the documentation[^] carefully.

I guess they needed that semicolon to parse the statement correctly as WITH can be used for other things too e.g. hints in selects:
SQL
SELECT * FROM MyTable WITH (NOLOCK)

or options in some commands:
SQL
ALTER TABLE MyTable REBUILD WITH (DATA_COMPRESSION = PAGE).

It is similar to MERGE[^] command which must always be terminated by a semicolon.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900