SQL error in subquery

时间:2015-09-14 16:12:37

标签: sql sql-server tsql

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

2 个答案:

答案 0 :(得分:3)

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;

答案 1 :(得分:2)

The SELECT * FROM tbl should have an alias defined.

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