【问题标题】:SQL- Create table does not work in SQL Server Management Studio SSMSSQL-创建表在 SQL Server Management Studio SSMS 中不起作用
【发布时间】:2018-08-23 10:11:30
【问题描述】:

由于某种原因,我无法在 SSMS 中从另一个表创建新表。

use master;

create table bop as
select *
from dbo.Data$
where [2016] is not null and 
      [Series Name] = 'Imports of goods and services (% of GDP)' or 
      [Series Name] = 'Exports of goods and services (% of GDP)'
order by [Country Name] asc;

它输出错误:

消息 156,第 15 级,状态 1,第 4 行
关键字“select”附近的语法不正确。

以前有人遇到过这个问题吗?我认为这是一个错误

【问题讨论】:

标签: sql sql-server


【解决方案1】:

对于 SQL Server,SQL 语法无效:

相反,您可以这样做:

select d.* into bop
from dbo.Data$ d
where [2016] is not null and 
      [Series Name] in ('Imports of goods and services (% of GDP)', 'Exports of goods and services (% of GDP)')
order by [Country Name] asc;

注意:

  • 如果您有多个易于读写的常量值,请使用IN 子句。
  • OR 逐一计算常量值,没有特定顺序,而IN 对列表进行排序。因此,IN 在某些情况下更快。

  • OR 将不包含 nulls 值(如果有),但 IN 将包含 null。因此,请根据您的实际需要选择其中之一。

【讨论】:

  • 您应该使用in 指出逻辑更改(这可能是OP 的意图)。
【解决方案2】:

试试下面的方法

SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0

您必须从您的查询中删除

create table bop as  ## this portion

你必须添加select * INTO bop

所以你的查询将是

select * INTO bop
from dbo.Data$
where [2016] is not null and 
    (  [Series Name] = 'Imports of goods and services (% of GDP)' or 
      [Series Name] = 'Exports of goods and services (% of GDP)'
    )
order by [Country Name]

您可以使用in 运算符来代替OR

select * INTO bop
    from dbo.Data$
    where [2016] is not null and 
          [Series Name] in ('Imports of goods and services (% of GDP)',
           'Exports of goods and services (% of GDP)')
    order by [Country Name]

您的错误分析

  • 消息 156,级别 15,状态 1,行 4 关键字附近的语法不正确 '选择'。

由于您使用错误的 sql 语句从其他表创建一个表,这就是 sqlserver 抛出 systax 错误的原因

【讨论】:

  • bop 表将保存在哪里?它不在“主”数据库中的表文件夹中
  • 可以指定数据库名
  • 但默认情况下它将在您的查询编辑器中选择的数据库上创建
【解决方案3】:

您的查询有几个问题。您想要的正确语法是:

select d.*
into bop
from dbo.Data$ d
where [2016] is not null and 
      [Series Name] in ('Imports of goods and services (% of GDP)', 'Exports of goods and services (% of GDP)');

注意以下几点:

  • SQL Server 使用select into,而不是create table as。这是您的基本语法错误。
  • 大概,你想要一个系列名称​​和 20161 not to beNULL.indoes this.ANDhas higher precedence thanOR`,所以你的逻辑会有所不同。
  • ORDER BY 不合适,除非目标表具有标识列。 SQL 表代表 无序 集合。唯一的排序是在 identity 列中的值。

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多