SQL Store将数据查询到一个表(临时或非临时)

时间:2015-06-15 06:57:45

标签: c# sql-server

我正在查询来自两个不同服务器的数据,现在我想将它存储在另一个表中,以便我可以在程序中将它用作我的参考表..(我在编程中使用ASP.NET)

看看我的命令,请告知该怎么做。

SELECT c.[pf_id]
      ,a.[RequestDate]
      ,c.[pf_carrierUsed]
      ,b.[PiecePrice] * b.[PartQuantity]
      ,c.[pf_type]
      ,c.[pf_resSupplier]
      ,c.[pf_resCustomer]
      ,c.[pf_trailerNum]
      ,b.[PartDesc]
      ,c.[pf_chargeBack]
      ,c.[pf_chargetoPlant]

FROM [CNCTC-WEB01].[NOP_PR].[dbo].[Requests] a
JOIN [CNCTC-WEB01].[NOP_PR].[dbo].[Parts] b on a.[RequestID] = b.[RequestID]
JOIN [PHRIZ-WEBAPP01].[PFTracking].[dbo].[Tbl_PFExcel] c on  b.[PartNumber] like '%'+c.pf_id+'%'
where a.[EntityName] like '%PTA' 
AND a.[RequestDate] between '2015-04-20 00:00:00.000' AND GETDATE()

此查询的结果是我想要存储在另一个表中,以便我可以使用它。

附加:

当我全部使用temp_tables时,我总是得到:

String or binary data would be truncated.

2 个答案:

答案 0 :(得分:3)

如果您的表存在,您可以使用INSERT,然后使用SELECT,或者您可以使用SELECT INTO来创建新表。

 INSERT INTO tempTable
 SELECT c.[pf_id]
  ,a.[RequestDate]
  ,c.[pf_carrierUsed]
  ,b.[PiecePrice] * b.[PartQuantity] AS totalPrice
  ,c.[pf_type]
  ,c.[pf_resSupplier]
  ,c.[pf_resCustomer]
  ,c.[pf_trailerNum]
  ,b.[PartDesc]
  ,c.[pf_chargeBack]
  ,c.[pf_chargetoPlant]

 FROM [CNCTC-WEB01].[NOP_PR].[dbo].[Requests] a
   JOIN [CNCTC-WEB01].[NOP_PR].[dbo].[Parts] b on a.[RequestID] =      b.[RequestID]
   JOIN [PHRIZ-WEBAPP01].[PFTracking].[dbo].[Tbl_PFExcel] c on  b.[PartNumber] like '%'+c.pf_id+'%'
   where a.[EntityName] like '%PTA' 
   AND a.[RequestDate] between '2015-04-20 00:00:00.000' AND GETDATE()

 SELECT c.[pf_id]
  ,a.[RequestDate]
  ,c.[pf_carrierUsed]
  ,b.[PiecePrice] * b.[PartQuantity] As TotalPrice
  ,c.[pf_type]
  ,c.[pf_resSupplier]
  ,c.[pf_resCustomer]
  ,c.[pf_trailerNum]
  ,b.[PartDesc]
  ,c.[pf_chargeBack]
  ,c.[pf_chargetoPlant]
 INTO tempTable
 FROM [CNCTC-WEB01].[NOP_PR].[dbo].[Requests] a
   JOIN [CNCTC-WEB01].[NOP_PR].[dbo].[Parts] b on a.[RequestID] =      b.[RequestID]
   JOIN [PHRIZ-WEBAPP01].[PFTracking].[dbo].[Tbl_PFExcel] c on  b.[PartNumber] like '%'+c.pf_id+'%'
   where a.[EntityName] like '%PTA' 
   AND a.[RequestDate] between '2015-04-20 00:00:00.000' AND GETDATE()

编辑。select into会自动为所有列创建tempTable并让其可供使用。

答案 1 :(得分:2)

您可以动态创建临时表,然后重复使用它:

select * into #someName
from someTable
join someOtherTable
...
where ...

如果您已有表,那么只需insert select声明:

insert into alreadyCreatedTable
select *
from someTable
join someOtherTable
...
where ...
相关问题