我需要向表中插入唯一的行,但是当我的Select使用2列的子查询时,我不知道如何使用不存在的地方。有没有办法做到这一点?
BTW:我确实对表有约束,并且无法插入重复项,但希望避免重复键错误。
我尝试了这种格式,但由于子查询,无法绑定列。
INSERT dbo.DataValue(DateStamp, ItemId, Value)
SELECT DateStamp, ItemId, Value
FROM dbo.tmp_holding_DataValue AS t
WHERE NOT EXISTS (SELECT 1 FROM dbo.DataValue AS d
WHERE DateStamp = t.DateStamp
AND ItemId = t.ItemId);
我的查询:
insert into App.DimRequirementComponentDetail_TST
(RequirementComponentSID, RequirementComponentDimensionSID, RequirementComponentDimensionValueSID,RequirementComponentDimensionValueText, Sta3n, ActiveFlag)
select (select RequirementComponentSID from App.DimRequirementComponent where name = @Measure ), -- 'PTSD PSY11'
(select RequirementComponentDimensionSID from App.DimRequirementComponentDimension where Name='ICD10 Diagnosis') ,
t1.ICD10SID,cast(t1.ICD10Code as varchar(max)),t1.Sta3n,'Y'--,t1.ICD10Description
from app.DimICD10 t1
where ICD10Code = @ICD10Code --'F32.5'
答案 0 :(得分:0)
我错过了什么或为什么你不能这样做?
INSERT INTO dbo.DataValue(DateStamp, ItemId, Value)
SELECT t.DateStamp, t.ItemId, t.Value
FROM dbo.tmp_holding_DataValue AS t
WHERE NOT EXISTS (SELECT 1 FROM dbo.DataValue AS d
WHERE d.DateStamp = t.DateStamp
AND d.ItemId = t.ItemId);
答案 1 :(得分:0)
我解决了这个问题。经过多次搜索后发现我的问题是引用了一个刚刚在where子句中选择的列。解决方案是将整个查询放在子查询中,然后引用。
Select * From
(
select (select RequirementComponentSID from App.DimRequirementComponent where name = @Measure) as RequirementComponentSID,
(select RequirementComponentDimensionSID from App.DimRequirementComponentDimension where Name='ICD10 Diagnosis') as RequirementComponentDimensionSID ,
ICD10SID ,cast(ICD10Code as varchar(max)) as ICD10Code,Sta3n,'Y' as ActiveFlag
from D01_VISN05.app.DimICD10 where ICD10Code = @ICD10Code
) RES
Where not exists( select 1 from App.DimRequirementComponentDetail_TST as d
join D01_VISN05.app.DimICD10 K on K.ICD10SID = RES.ICD10SID
where RES.RequirementComponentSID = d.RequirementComponentSID
and RES.RequirementComponentDimensionSID = d.RequirementComponentDimensionSID
and RES.sta3n = d.sta3n
and RES.ICD10SID= K.ICD10SID
and RES.ICD10Code= K.ICD10Code
and RES.ActiveFlag = D.ActiveFlag
);