Create Table As With

安稳与你 提交于 2019-12-11 08:39:54

问题


Im writing sql query and i have issue which i cannot fix.

I'm trying this:

CREATE TABLE a
AS
WITH cteCandidates (Miejscowosc, Ulica, NrDomu, KodPocztowy)
  AS
  (
    SELECT Miejscowosc, Ulica, NrDomu, KodPocztowy
    FROM Gimnazja
    INTERSECT
    SELECT Miejscowosc, Ulica, NrDomu, KodPocztowy
    FROM SzkolyPodstawowe
  )
 Select
  e.Lp as 'Gimnazja',
  s.Lp as 'Szkoly Podstawowe'
FROM
  Gimnazja AS e
  INNER JOIN cteCandidates AS c
    ON e.Miejscowosc = c.Miejscowosc AND e.Ulica = c.Ulica AND e.NrDomu = c.NrDomu AND e.KodPocztowy = c.KodPocztowy
  INNER JOIN SzkolyPodstawowe s
        ON s.Miejscowosc = e.Miejscowosc AND s.Ulica = e.Ulica AND s.NrDomu = e.NrDomu AND s.KodPocztowy = e.KodPocztowy
        Order By 'Gimnazja'

And errors which i get:

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'AS'.
Msg 319, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.

And i don't know why. I think that my query is proper but clearly not, and i don't understand why.


回答1:


Perhaps you want:

WITH cteCandidates (...)
SELECT
   e.Lp as 'Gimnazja',
   s.Lp as 'Szkoly Podstawowe'
INTO a                          -- < -- table created here
FROM
   Gimnazja AS e
   INNER JOIN ...;



回答2:


Are you trying to create a view? Then it'd work...




回答3:


CREATE TABLE is used to define a table schema. The WITH keyword is used to define a CTE retrieval of data. These are two completely different operations.

If you need a table within your SQL look at http://msdn.microsoft.com/en-us/library/ms174979.aspx to see the syntax for defining it. You then may populate it with INSERT but that's highly unlikely to be from a CTE ( see below)

Usually with CTEs you don't need to insert the data into a table; in the statement immediately after it you can just use the data retrieved as the table has been temporarily defined and populated for you automatically.

A CTE can be used to define a VIEW - see Create view based on hierarchy / used of CTE for an example



来源:https://stackoverflow.com/questions/9429503/create-table-as-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!