简体   繁体   English

SQL 服务器,在 TSQL 中创建临时表时出现问题

[英]SQL Server, Problem creating temp table in TSQL

Hi when i execute the following TSQL, i get the error message below.嗨,当我执行以下 TSQL 时,我收到以下错误消息。 But there is nothing wrong with the SQL syntax is there?但是 SQL 语法没有错吗?

create table #tb ([t1] tinyint, [t2] varchar(50))
insert into #tb values
    (1, 'a'), 
    (2, 'b')

Msg 102, Level 15, State 1, Line 3 Incorrect syntax near ','.消息 102,级别 15,State 1,第 3 行“,”附近的语法不正确。

There is nothing else in the SQL query window. SQL 查询 window 中没有其他内容。 Running SQL Server 2005.运行 SQL 服务器 2005。

As jmoreno mentions, the VALUES (), () syntax is SQL Server 2008+ supported but you tagged this as SQL Server 2005.正如 jmoreno 所提到的, VALUES (), ()语法是 SQL Server 2008+ 支持,但您将其标记为 SQL Server 2005。

Use:利用:

CREATE TABLE #tb ([t1] tinyint, [t2] varchar(50))

INSERT INTO #tb 
SELECT 1, 'a'
UNION ALL
SELECT 2, 'b'

It's also possible to do this in a single query, using the SELECT... INTO clause , but the temp table can't already exist:也可以在单个查询中执行此操作,使用SELECT... INTO子句,但临时表不能已经存在:

SELECT *
  INTO #tb
  FROM (SELECT CAST(1 AS TINYINT) AS t1, 
               CAST('a' AS VARCHAR(50)) AS t2
        UNION ALL
        SELECT 2, 'b') x

Try this:尝试这个:

create table #tb ([t1] tinyint, [t2] varchar(50));
insert into #tb ([t1], [t2])
values(1, 'a'), (2, 'b')

You need to specify the columns that you're inserting into.您需要指定要插入的列。

//EDIT //编辑

Sorry, SQL 2005 syntax below.对不起,SQL 2005 语法如下。 It's not nearly as elegant.它几乎没有那么优雅。

CREATE TABLE #tb ([t1] TINYINT, [t2] VARCHAR(50));
INSERT INTO #tb
SELECT 1, 'a'
UNION ALL
SELECT 2, 'b'

You say you're using SQL 2005, but the VALUES (), () syntax wasn't implemented until 2008.您说您使用的是 SQL 2005,但 VALUES (), () 语法直到 2008 年才实现。

Looks like you're trying to insert two rows, so you need to insert the first row and then the second instead of trying to squeeze it all into one:看起来您正在尝试插入两行,因此您需要先插入第一行,然后再插入第二行,而不是尝试将其全部压缩为一个:

CREATE TABLE #tb ([t1] TINYINT, [t2] VARCHAR(50));
INSERT INTO #tb([t1],[t2]) VALUES (1, 'a'); --row 1
INSERT INTO #tb([t1],[t2]) VALUES (2, 'b'); --row 2

--see if it worked
SELECT [t1], [t2] 
FROM #tb

--clean up the temp table when you're done
DROP TABLE #tb

SELECT t.field1, t.field2 INTO #myTempTable SELECT t.field1, t.field2 INTO #myTempTable

FROM myDB.myOwner.myTable t FROM myDB.myOwner.myTable t

WHERE...在哪里...

ORDER BY t.field1, t.field2;按 t.field1、t.field2 排序;

-- use ##myTempTable as the name if you want your table to be GLOBAL. -- 如果您希望您的表是 GLOBAL,请使用 ##myTempTable 作为名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM