基于查询SQL Server创建新表

时间:2015-08-24 15:39:35

标签: sql sql-server tsql

我有一个查询

with x as 
(select row_number() over(partition by FirstName order by Investment_DT desc) as rn, *
from [dbSuppHousing].[dbo].[tblABC])
select Login_Name
      ,r.Role_Name
      ,Investment_DT
      ,FirstName     
      ,LastName
      ,Login_Name
      ,Investment_DT
      ,Investment_ID
from x join tblUsers t 
on t.UserName = x.Login_Name

join tblUser_Roles ur on t.User_Id=ur.USER_ID
join tblRoles r on r.Role_Id=ur.Role_ID
where x.rn = 1

order by x.FirstName

我想将此查询的结果按原样插入到另一个表中。

通常我会使用如下查询:

insert  into tblABC2
select * from tblABC  

但我不知道如何在这种情况下执行此操作,这是一个以with x as开头的查询

3 个答案:

答案 0 :(得分:1)

with x as 
(select row_number() over(partition by FirstName order by Investment_DT desc) as rn, *
from [dbSuppHousing].[dbo].[tblABC])
select Login_Name
      ,r.Role_Name
      ,Investment_DT
      ,FirstName     
      ,LastName
      ,Login_Name
      ,Investment_DT
      ,Investment_ID
into #temptable
from x join tblUsers t 
on t.UserName = x.Login_Name
join tblUser_Roles ur on t.User_Id=ur.USER_ID
join tblRoles r on r.Role_Id=ur.Role_ID
where x.rn = 1
-- order by x.FirstName 

您可以使用into插入所需的表格。另请注意,执行此操作(已注释掉)时,您无法执行order by

答案 1 :(得分:0)

with x as (...) insert into tbl select * from x

因此,insert应该直接在查询中使用的所有CTE之后。

答案 2 :(得分:0)

您只需将insert语句放在公用表表达式(CTE)和select语句之间:

with x as 
(select row_number() over(partition by FirstName order by Investment_DT desc) as rn, *
from [dbSuppHousing].[dbo].[tblABC])

/*
    place insert statement here
*/

select Login_Name
      ,r.Role_Name
      ,Investment_DT
      ,FirstName     
      ,LastName
      ,Login_Name
      ,Investment_DT
      ,Investment_ID
from x join tblUsers t 
on t.UserName = x.Login_Name

join tblUser_Roles ur on t.User_Id=ur.USER_ID
join tblRoles r on r.Role_Id=ur.Role_ID
where x.rn = 1

order by x.FirstName

如果您在SQL Server 2008+上运行此操作,则需要确保CTE之前的任何语句都以分号结束。