Kamster
Kamster

Reputation: 127

SQL error in subquery

The following code

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

SELECT *
INTO #temp
FROM (SELECT * FROM tbl)

Gives me a syntax error right after last parenthesis

I don't understand why at all

Upvotes: 1

Views: 41

Answers (2)

Lukasz Szozda
Lukasz Szozda

Reputation: 175596

You don't need subquery:

SELECT * 
INTO #temp
FROM tbl;

Or add alias:

SELECT t.*
INTO #temp
FROM (SELECT * FROM tbl) AS t

You can also use CTE for more complex subqueries:

;WITH cte AS
(
   SELECT *
   FROM tbl
)
SELECT cte.*
INTO #temp
FROM cte;

Upvotes: 3

Vamsi Prabhala
Vamsi Prabhala

Reputation: 49260

The SELECT * FROM tbl should have an alias defined.

SELECT t.*
INTO #temp
FROM (SELECT * FROM tbl) t

Upvotes: 2

Related Questions