我试图将丢失的数据添加到数据库中,因此试图通过查询来收集这些丢失的数据。
在我的Excel工作表中,我有两列:col A
填充有组件代码,而col J
保留了它们各自的资产类型代码。
我想在一个查询中找到所有不存在的组件资产类型组合。
目前,我正在遍历excel表,如以下示例所示:
arr = Range("B3:J5000")
For i = 1 To 5000-2
Set rs = cnn.Execute("Select Top 1 AT.Code From astComponents C Join astAssetTypes AT ON AT.Id = C.AssetTypeId Where C.Code = '" & arr(i, 1) & "' And AT.Code = '" & arr(i, 9) & "'")
If rs.EOF Then
'Missing data was found
End If
Next i
但是,这并不令我满意。我想最后得到一个记录集,其中缺少组件-资产类型组合。这将大大提高我的程序速度(快120倍)
我尝试使用Except
,但是没有得到我期望的记录:
Select Distinct C.Code, AT.Code
FROM dbo.astComponents C
JOIN dbo.astAssetTypes AT ON AT.Id = C.AssetTypeId
WHERE (C.Code= '0738.D100' AND AT.Code = '0738.M00_03.03') Or (C.Code= '0738.D101' AND AT.Code = '0738.L00_04.04')
Except Select C.Code, AT.Code From astComponents C Join astAssetTypes AT ON AT.Id = C.AssetTypeId
编辑
如前所述,期望的输出应该是缺少的组件-资产类型组合。示例:
Component Asset Type
0738.D101 0990.D10_03.03
0150.C101 0738.L00_04.04
SQL-Fiddle
任务:检查小提琴数据库中是否存在以下组件-资产类型组合。如果没有,请将这些组合添加到输出中。
Component Asset Type
0738.D100 0990.D10_03.03
0738.D101 0990.D10_03.03
0150.C101 0738.L00_04.04
0738.L004 0738.M00_03.03
0990.D103 0738.M00_03.03
答案 0 :(得分:0)
不是最终答案,因为下面的方法很慢
在此方法中,我使用一个循环来填充变量,该变量有助于使用所有应检查的组件-资产类型组合来填充临时表。然后,我使用CTE将数据库中的值与temp表进行比较。
创建临时表并执行第二个查询持续5秒钟(#Temp
中有1250条记录),我认为这太慢了
arr = Range("B3:J" & LRow)
For i = 1 To LRow - 2
ComponentCodeTemp = ComponentCodeTemp & "Insert Into #Temp (Component, AssetType) Values ('" & arr(i, 1) & "','" & arr(i, 9) & "');"
Next i
'Query
Set rs = getdata("Create Table #Temp(Component nvarchar(50) Collate Latin1_General_BIN, AssetType nvarchar(50) Collate Latin1_General_BIN) " & ComponentCodeTemp & _
"; With Compare As (Select T.* From #Temp T), DBD As (Select Distinct Compare.Component, Compare.AssetType From astComponents C Join astAssetTypes AT ON AT.Id = C.AssetTypeId Right Join #Temp Compare ON Compare.AssetType = AT.Code And Compare.Component = C.Code Where C.Code is null) " & _
"Select * From DBD")
SQL查询的更好标记:
WITH
Compare AS (
Select T.* FROM #Temp T
),
DBD AS (
Select Distinct Compare.Component, Compare.AssetType From astComponents C
Join astAssetTypes AT ON AT.Id = C.AssetTypeId
Right Join #Temp Compare ON Compare.AssetType = AT.Code And Compare.Component = C.Code
Where C.Code is null
)
Select * From DBD