62

I have a view that I want to create a table from in SQL Enterprise Manager, but I always get an error when I run this query:

CREATE TABLE A 
AS
(SELECT top 10 FROM dbo.myView)

So far the error is: "syntax error at 'as'"

View is too large. Is it possible to use a top 10?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
tdjfdjdj
  • 2,391
  • 13
  • 44
  • 71
  • And *what error do you get*?! – Daniel Hilgarth Jul 14 '11 at 14:05
  • what error are you getting when you try this? – Sai Kalyan Kumar Akshinthala Jul 14 '11 at 14:06
  • select * into A from dbo.myView where 1 = 2 will give you an empty table – t-clausen.dk Jul 14 '11 at 14:18
  • Your question answered on this [Question](https://stackoverflow.com/questions/21547/in-sql-server-how-do-i-generate-a-create-table-statement-for-a-given-table). [See this answer will help you](https://stackoverflow.com/a/317864/4104167). script on this answer get you scripts for generate all tables in database. If you modify last where condition, you can get scripts for create table from views. [The next answer](https://stackoverflow.com/a/21551/4104167) makes it easier for you. You can set table or view name and run script then result return create table script for you. – amin Jul 16 '17 at 10:31

9 Answers9

116

SQL Server does not support CREATE TABLE AS SELECT.

Use this:

SELECT  *
INTO    A
FROM    myview

or

SELECT  TOP 10
        *
INTO    A
FROM    myview
ORDER BY
        id
Quassnoi
  • 413,100
  • 91
  • 616
  • 614
61

If you just want to snag the schema and make an empty table out of it, use a false predicate, like so:

SELECT * INTO myNewTable FROM myView WHERE 1=2
Pittsburgh DBA
  • 6,672
  • 2
  • 39
  • 68
14

In SQL SERVER you do it like this:

SELECT *
INTO A
FROM dbo.myView

This will create a new table A with the contents of your view.
See here for more info.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
7

To create a table on the fly us this syntax:

SELECT *
INTO A
FROM dbo.myView
Keith
  • 2,618
  • 4
  • 29
  • 44
3

If you want to create a new A you can use INTO;

select * into A from dbo.myView
Alex K.
  • 171,639
  • 30
  • 264
  • 288
3
SELECT * INTO [table_a] FROM dbo.myView
mikey
  • 5,090
  • 3
  • 24
  • 27
3

Looks a lot like Oracle, but that doesn't work on SQL Server.

You can, instead, adopt the following syntax...

SELECT
  *
INTO
  new_table
FROM
  old_source(s)
Brian
  • 6,910
  • 8
  • 44
  • 82
MatBailie
  • 83,401
  • 18
  • 103
  • 137
1
Select 
    MonthEndDate MED,  
    SUM(GrossBalance/1000000) GrossBalance,
    PortfolioRename PR 
into 
    testDynamic 
from 
    Risk_PortfolioOverview  
    Group By MonthEndDate, PortfolioRename
andrewsi
  • 10,807
  • 132
  • 35
  • 51
javal
  • 11
  • 1
-1
INSERT INTO table 2
SELECT * FROM table1/view1
Zoe
  • 27,060
  • 21
  • 118
  • 148
amstegraf
  • 597
  • 1
  • 5
  • 11