Avatar of deborahhowson00
deborahhowson00

asked on 

sql semi-colon WITH error syntax

Hi, I have a problem with the following code, giving the error below.  If I add a semi-colon before 'WITH' as it says to do when I've looked up the problem, it then returns that as an error so am stuck!  Any ideas of the correct syntax?

IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL
    DROP TABLE #TempTable

CREATE TABLE #TempTable(
OrderBy int,
TotalUsers int,
FinancialYear int,
CombYear varchar(20),
Measure varchar(150))



INSERT INTO #TempTable (OrderBy, TotalUsers, FinancialYear, CombYear, Measure)

;With myTable as 
	(SELECT '1' AS OrderBy, count( D1.UserID) AS TotalUsers, FinYear, CombYr, 'Number of Active Accounts Created in Period' AS Name
FROM ext_User AS D1
INNER JOIN Dates
ON CONVERT(VARCHAR, UserCreated, 110) = CONVERT(VARCHAR, Date, 110)
where UserCreated < GetDate() and UserStatusCode = 'A'
GROUP BY FinYear, CombYr)

Select OrderBy, TotalUsers, FinYear, Sum(TotalUsers) OVER(ORDER BY FinYear) AS RollingTotal, CombYr, Name
from myTable

SELECT * FROM #TempTable

Open in new window



Error is:
Msg 156, Level 15, State 1, Line 15
Incorrect syntax near the keyword 'With'.
Msg 319, Level 15, State 1, Line 15
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.



With the semi-colon code is:

IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL
    DROP TABLE #TempTable

CREATE TABLE #TempTable(
OrderBy int,
TotalUsers int,
FinancialYear int,
CombYear varchar(20),
Measure varchar(150))



INSERT INTO #TempTable (OrderBy, TotalUsers, FinancialYear, CombYear, Measure)

;With myTable as 
	(SELECT '1' AS OrderBy, count( D1.UserID) AS TotalUsers, FinYear, CombYr, 'Number of Active Accounts Created in Period' AS Name
FROM ext_User AS D1
INNER JOIN Dates
ON CONVERT(VARCHAR, UserCreated, 110) = CONVERT(VARCHAR, Date, 110)
where UserCreated < GetDate() and UserStatusCode = 'A'
GROUP BY FinYear, CombYr)

Select OrderBy, TotalUsers, FinYear, Sum(TotalUsers) OVER(ORDER BY FinYear) AS RollingTotal, CombYr, Name
from myTable


SELECT * FROM #TempTable

Open in new window


Error message is:
Msg 102, Level 15, State 1, Line 15
Incorrect syntax near ';'.

Thanks in advance
Microsoft SQL ServerSQL

Avatar of undefined
Last Comment
ste5an

8/22/2022 - Mon