【问题标题】:SQL 2008 R2 CTE syntax error in a SELECT statementSELECT 语句中的 SQL 2008 R2 CTE 语法错误
【发布时间】:2014-06-27 15:46:35
【问题描述】:

这个问题是基于我之前的问题

SQL server 2008 R2, select one value of a column for each distinct value of another column

关于 SQL Server 2008 上的 CTE。

   WITH my_cte(id_num, rn) AS (
      SELECT name, 
      rn = ROW_NUMBER() OVER (PARTITION BY a.name ORDER BY newid())
            FROM my_table as a
      )
   SELECT id_num FROM my_cte WHERE rn = 1

   INSERT INTO #temp_table 
   SELECT a.address from another_table as a,
            id_num from my_cte  -- here, I got error!!!

为什么会出错:关键字“from”附近的语法不正确。

我需要获取一个新表,其中一列来自 another_table,一列来自 my_cte。

例如

 address (from another_table)    id_num (from my_cte)
  city_1                        65 
  city_1                        36
  city_2                        65
  city_2                        36
  city_3                        65
  city_3                        36

我应该使用什么样的连接来获取上表,以便每个地址都与 CTE 中的所有 id_num 相关联?假设 id_num 只有 65 和 36 两个值。 my_cte 没有地址列。

任何帮助将不胜感激。

【问题讨论】:

  • 这到底是想做什么? SELECT * FROM ( SELECT a.address from another_table as a, id_num from my_cte -- **I got error: Incorrect syntax near the keyword 'from'.** ) as t
  • 是的,我明白了..这个SELECT a.address from another_table as a, id_num from my_cte 无效...我在问你打算在这里做什么。
  • 您是否已经创建了临时表,或者您正在尝试选择进入?

标签: sql sql-server sql-server-2008


【解决方案1】:

CTE 只能用于紧跟其后的语句中。执行SELECT id_num FROM my_cte WHERE rn = 1 后,cte 不再存在。

【讨论】:

    【解决方案2】:

    CTE 仅针对单个查询存在。但是您可以将它与insert 以及select 一起使用:

       WITH my_cte(id_num, rn) AS (
          SELECT name, ROW_NUMBER() OVER (PARTITION BY a.name ORDER BY newid()) as rn
          FROM my_table as a
       )
       INSERT INTO #temp_table 
           SELECT a.address, id_num
           from another_table as a JOIN
                my_cte
                on a.name = my_cte.name;
    

    【讨论】:

    • INSERT中的选择仍然无效。
    • @Gordon Linoff,我遇到了同样的错误:关键字'from' my_cte 附近的语法不正确。
    • 这是因为有两个 FROM 子句
    • 您的最后一个SELECT 中有两个FROM 子句。
    • 我需要从两个不同的表中插入两列,该怎么做?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多