使用Select * Into将数据插入临时表

时间:2013-02-18 11:02:06

标签: sql sql-server

我想将数据插入到临时表中,因为我正在使用select * into语法。

但是我收到了错误:

Msg 102, Level 15, State 1, Line 8
Incorrect syntax near ')'.

虽然单个查询执行成功。

代码:

Create Table #_Total
(
A   Int,
B   Int,
C   Int,
D   Int
)

Select * InTo #_Total From(
Select 
Sum(Case When Closed=0 And ISNULL(VendorTicketNo,'')='' Then 1 Else 0 End),
Sum(Case When Closed=1 And TicketType<>8 AND ISNULL(VendorTicketNo,'')<>'' Then 1 Else 0 End),
Sum(Case When Closed=1 And CAST(ClosedOn As DATE)= CONVERT(VARCHAR(8),GETDATE(),112) Then 1 Else 0 End),
Sum(Case When Closed=0 And TicketType=8 Then 1 Else 0 End)
From ALBATMStatus.dbo.Ticket
)

Select * From #_Total

数据库 - SQL SERVER 2008

2 个答案:

答案 0 :(得分:2)

由于您事先创建了表格,因此必须使用

INSERT INTO

试试这个

Create Table #_Total
(
A   Int,
B   Int,
C   Int,
D   Int
)

Insert Into #_Total 
Select * From(
Select 
Sum(Case When Closed=0 And ISNULL(VendorTicketNo,'')='' Then 1 Else 0 End),
Sum(Case When Closed=1 And TicketType<>8 AND ISNULL(VendorTicketNo,'')<>'' Then 1 Else 0 End),
Sum(Case When Closed=1 And CAST(ClosedOn As DATE)= CONVERT(VARCHAR(8),GETDATE(),112) Then 1 Else 0 End),
Sum(Case When Closed=0 And TicketType=8 Then 1 Else 0 End)
From ALBATMStatus.dbo.Ticket
) AS a

Select * From #_Total

拉​​吉

答案 1 :(得分:1)

正如@Raj所说,您使用Createselect into

然而他错过了as ALIAS_NAME。如下:

Create Table #_Total
(
A   Int,
B   Int,
C   Int,
D   Int
)

Insert Into #_Total 
Select * From(
Select 
Sum(Case When Closed=0 And ISNULL(VendorTicketNo,'')='' Then 1 Else 0 End) A,
Sum(Case When Closed=1 And TicketType<>8 AND ISNULL(VendorTicketNo,'')<>'' Then 1 Else 0 End) B,
Sum(Case When Closed=1 And CAST(ClosedOn As DATE)= CONVERT(VARCHAR(8),GETDATE(),112) Then 1 Else 0 End) C,
Sum(Case When Closed=0 And TicketType=8 Then 1 Else 0 End) D
From ALBATMStatus.dbo.Ticket
) as q1

Select * From #_Total