-1

I need to create a #temp table before my list of CTE:s start so that I can use it in the end to perform calculations.

This is what I have written so far:

SELECT DISTINCT

SUM(X+Y) AS Total

INTO #Summary
FROM Table

WITH CTE_START AS
(
  SELECT DISTINCT *
  FROM TableX
)

....

I have even tried creating my #Summary as a CTE and then writing INTO before FROM. It does not work.

I have looked at similar questions on:CTE&Temp Table

I have not found anything helpful. How can I create a #temp table before my WITH CTE_START begins processing?

1
  • 2
    Why doesn't the code that you have written work? I see no problem with it.
    – usr
    Jun 25, 2015 at 12:11

1 Answer 1

5

You need to terminate the statement before the CTE with a semicolon, otherwise SQL Server doesn't know the WITH isn't part of the previous statement, for example part of a table hint.

For example:

SELECT DISTINCT SUM(X+Y) AS Total INTO #Summary FROM Table;

WITH CTE_START AS ( SELECT DISTINCT * FROM TableX ) 
SELECT * FROM CTE_START
10
  • 1
    It's a good practice to begin CTEs with a semicolon, i.e. ;WITH. I thought it was worth mentioning that. Jun 25, 2015 at 12:14
  • It is funny that I did not use semicolon after the AND line of code. I simply thought it would not work. Sometimes the easier way works better than trying to create additional CTE or #Temp. Thank you. Problem solved. Jun 25, 2015 at 12:19
  • @EvaldasBuinauskas - yes, this is a good point. Personally, I find it ugly, as the semicolon really belongs to the previous statement, but this is just a matter of personal taste.
    – Ed B
    Jun 25, 2015 at 12:19
  • It's a habit that's worth getting into: "Although the semicolon is not required for most statements in this version of SQL Server, it will be required in a future version." Jun 25, 2015 at 12:38
  • 1
    @usr - I think if this is going to happen, it'll be along the lines of, announced in SQL Server 2014, not implemented until 2 versions later (2018?), then supported as a compatibility level 13 or 14 for another three versions after that, so not likely to cause a real need to change any code for another six or seven years, by which time we're in the year 2025, and we'll all be meat-slaves to the robot overlords anyway.
    – Ed B
    Jun 25, 2015 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.