57

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,438
  • 68
  • 55
  • 126
tdjfdjdj
  • 2,341
  • 12
  • 44
  • 69
  • 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

111

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
  • 398,504
  • 89
  • 603
  • 604
59

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,542
  • 2
  • 38
  • 67
12

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
  • 166,158
  • 40
  • 312
  • 426
7

To create a table on the fly us this syntax:

SELECT *
INTO A
FROM dbo.myView
Keith
  • 2,598
  • 4
  • 27
  • 44
3

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

select * into A from dbo.myView
Alex K.
  • 165,803
  • 30
  • 257
  • 277
3
SELECT * INTO [table_a] FROM dbo.myView
mikey
  • 4,968
  • 3
  • 22
  • 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,562
  • 6
  • 41
  • 79
MatBailie
  • 77,948
  • 17
  • 98
  • 134
1
Select 
    MonthEndDate MED,  
    SUM(GrossBalance/1000000) GrossBalance,
    PortfolioRename PR 
into 
    testDynamic 
from 
    Risk_PortfolioOverview  
    Group By MonthEndDate, PortfolioRename
andrewsi
  • 10,995
  • 132
  • 34
  • 49
javal
  • 11
  • 1
0
INSERT INTO table 2
SELECT * FROM table1/view1
Zoe stands with Ukraine
  • 25,310
  • 18
  • 114
  • 149
amstegraf
  • 560
  • 1
  • 4
  • 11