将一个表中的列复制到另一表中的另一列

时间:2019-02-13 18:13:45

标签: c# sql sql-server

我有三个表,分别有列

t参考文献:

 PK_Reference
 FK_ReferenceType
 ReferenceValue
 thePKofMain_FK

tReferencesTypes:

 PK_ReferenceType
 ReferenceName

tMain:

 PK_Main
 FirstReferenceValue
 SecondReferenceValue
 ThirdReferenceValue

三个引用已经变得非常重要,以至于它们必须转到tMain表中。假设来自tReferenceTypes的三个引用的PK是321、654和987。我需要将tReference的引用值复制到tMain表中,其中每个引用现在都有自己的列,但是我必须确保添加从tReference到正确的PK_Main的值,该值应该与tReference表中的theofofPK_Main_FK相同,并且是amtReferenceType PK。

我需要这样的东西...

UPDATE tMain
SET 
tMain.FirstReferenceValue = (SELECT ReferenceValue FROM tReference WHERE FK_referenceType =321)
FROM  tReference 
WHERE tReference. thePKofMain_FK = tMain.PK_Main

但是我得到的消息很有意义:

  

子查询返回了多个值。当   子查询遵循=,!=,<,<=,>,> =或使用子查询时   作为一种表达。该声明已终止。

UPDATE tMain
SET 
tMain.FirstReferenceValue = (SELECT ReferenceValue FROM tReference
JOIN tReference on tReference.thePKofMain_FK = tMain.PK_Main
WHERE FK_referenceType =9001649
WHERE FK_referenceType =321)
FROM  tReference 
WHERE tReference. thePKofMain_FK = tMain.PK_Main
  

信息209,级别16,状态1,第18行。列名称不明确   “ FK_referenceType”。消息209,第16级,状态1,第15行。   列名称“ ReferenceValue”。

或者我应该考虑在C#中执行此操作?

2 个答案:

答案 0 :(得分:0)

一些示例数据:

t参考文献:

PK_参考

 123    
 456    
 789 

FK_ReferenceType:

 321    
 654   
 987 

ReferenceValue

 111    
 a    
 1 

--------------为什么由于某些参考值相同而出现第一条错误消息

 111
 c
 2

Main_FK的PK

 147    
 258    
 369 

tReferencesTypes:

PK_ReferenceType

 321    
 654    
 987

参考名称:

FirstReferenceValue     
SecondReferenceValue    
ThirdReferenceValue 

tMain:

PK_Main:

 147    
 258    
 369 

FirstReferenceValue:

Empty

SecondReferenceValue:

Empty

ThirdReferenceValue:

Empty

存在ReferenceValue的重复项,为什么第一个sql查询不起作用,但是即使存在相同referenceValue的重复项,我仍然需要将其复制到新表中

当我尝试发布问题时,它在WHERE FK_referenceType = 9001649中意外键入的第二个查询。

答案 1 :(得分:0)

使用枢轴获取tMain值

INSERT tMain (PK_Main, FirstReferenceValue, SecondReferenceValue, ThirdReferenceValue)
SELECT P.thePKofMain_FK, P.[321], P.[654], P.[987]
FROM (
    SELECT FK_ReferenceType, ReferenceValue, thePKofMain_FK
    FROM tReference
) T
PIVOT (
    MAX(ReferenceValue) FOR FK_ReferenceType IN ([321], [654], [987])
) P