Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT INTO with subquery

Regarding SELECT INTO in SQL Server

The following throw an error Incorrect syntax near ')'.

SELECT * INTO Sales.MyTable FROM 
(SELECT TOP(100) * FROM Sales.Customer)

The following will pass

With tempCust AS
(
SELECT TOP(100) * FROM Sales.Customer
)
SELECT * INTO Sales.MyTable FROM tempCust

What is the rule behind that ?

like image 498
Kenny Avatar asked Sep 15 '15 10:09

Kenny


People also ask

Can we use subquery in SELECT clause?

You can use subqueries in SELECT, INSERT, UPDATE, and DELETE statements wherever expressions are allowed. For instance, you can use a subquery as one of the column expressions in a SELECT list or as a table expression in the FROM clause.

How do you write a subquery in a SELECT statement?

A subquery is a SELECT statement embedded in another SQL statement, such as a SELECT, INSERT, DELETE, or UPDATE statement. The set of value(s) returned by the inner SELECT statement are passed to the outer SQL statement. The inner SELECT statement is always embraced in parentheses.

Can you use a subquery in an insert statement?

Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date or number functions.

How do I SELECT within a SELECT in SQL?

The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another subquery. A subquery is usually added within the WHERE Clause of another SQL SELECT statement. You can use the comparison operators, such as >, <, or =.


1 Answers

Can you add an alias to your subquery like shown below and then give it a try..

SELECT * INTO Sales.MyTable FROM 
(SELECT TOP(100) * FROM Sales.Customer) as abc
like image 60
Amnesh Goel Avatar answered Oct 13 '22 01:10

Amnesh Goel