【问题标题】:Is there any way to create a temporary table using subquery in SQL?有没有办法在 SQL 中使用子查询创建临时表?
【发布时间】:2021-05-07 14:50:07
【问题描述】:

对于一个特定的问题,我想要下表中的值,

number  |  number_in_words
--------------------------
   1    |        one
   2    |        two
   3    |        three
   4    |        four
   5    |        five
   6    |        six
   7    |        seven
   8    |        eight
   9    |        nine
   0    |        zero

但是数据库中没有这样的表,我不应该在数据库中创建表。

使用下面的子查询,我得到了只有一行的表,有什么方法可以使用类似的查询来获取整个上表?

(select '1' as number, 'one' as number_in_words)

【问题讨论】:

  • 查看VALUES 以创建一个您可以加入的动态虚拟表
  • 你可以使用一个临时表,或者一个 CTE 或者只是 select+union all 作为子查询。

标签: sql sql-server database


【解决方案1】:

您可以这样做,方法是在子查询中使用从值中选择来准备它:

(SELECT * FROM (VALUES (1,'one'),(2,'two'),(3,'three'),(4,'four'),(5,'five')) numbertable(number,number_in_words))

【讨论】:

  • 正确的说法是table value constructor
  • 请注意,VALUES 表结构不是临时表。临时表在创建它的范围内持续存在,或者直到它被删除。一个表值构造器只能在语句中被引用,而作用域,它是定义的
【解决方案2】:

我认为你不能在 DML 中使用 DDL(创建表),尝试检查“WITH”公用表表达式,在幕后,WITH 子句将创建一个临时表,您可以在子查询中引用它。

https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-ver15

【讨论】:

  • 感谢您的评论,从您的评论中我又转了一圈,选择'1'作为数字,'一'作为数字_in_words union select'2'作为数字,'two'作为number_in_words union select '3' 作为数字,'三' 作为 number_in_words union 选择'4' 作为数字,'four' 作为 number_in_words union 选择'5' 作为数字,'5' 作为 number_in_words union
【解决方案3】:

您也可以使用表变量。

DECLARE @lookup TABLE (numVal INT NOT NULL, strVal varchar(10))
INSERT INTO @lookup(numVal, strVal) VALUES (1, 'one'), (2, 'two'), (3, 'three') --etc

-- and then use the value similar to a normal table using joins or whatever
select l.strVal --,  other values
from yourTable as yt INNER JOIN @lookup as l ON yt.numericValue = l.numVal

【讨论】:

    【解决方案4】:

    任何可以查询数据库的人都可以创建临时表。研究临时表,您可以制作一个完全一样的表。

    CREATE TABLE #temp (number int PRIMARY KEY, number_in_words varchar(10))
    INSERT INTO #temp (number, number_in_words) VALUES 
     (1, 'one')
    ,(2, 'two')
    ,(3, 'three')
    

    等等。

    然后当你完成时:

    DROP TABLE #temp
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 2023-01-20
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多