How to fix 'ODCB call failed during OpenRecordSet' - sql

I am currently working on some changes to an existing Access(vba) application. But suddenly I am running into an ODCB call failed error while running a QueryDef. The tables are linked to a SQL server database.
I've tried resetting the links to the tables via the linked table manager.
Also debugged to see if the query was indeed defined and that the SQL within is correct.
Call makePassThroughQuery("qryName", qSQL, True)
Dim SQL As String
SQL = "select * from qryName"
Set rsNew = DB.OpenRecordset(SQL, dbOpenDynaset, dbSeeChanges)
' continue to use rsNew
The makePassThroughQuery function looks like this:
Function makePassThroughQuery(qryName As String, SQLString As String,
Optional isSQL As Boolean = True,
Optional ConnectString As String = "string",
Optional timeout As Integer = 120)
Dim isTestingEnvironment As Boolean
isTestingEnvironment = True
If isSQL = False Then
With CurrentDb
On Error Resume Next
.QueryDefs.Delete (qryName)
On Error GoTo 0
Dim qdfNew As Object
Set qdfNew = .CreateQueryDef(qryName, SQLString)
.Close
End With
Else
Dim curDB As Database, curQdef As QueryDef
' Dim ConnectString As String
'ConnectString = "string"
Set curDB = CurrentDb
On Error Resume Next
CurrentDb.QueryDefs.Delete (qryName)
On Error GoTo 0
Set curQdef = curDB.CreateQueryDef(qryName)
curQdef.Connect = ConnectString '& ";Returns Records=false;"
curQdef.ODBCTimeout = timeout
curQdef.sql = SQLString
curQdef.Close
End If
End Function
The call should work since this is the same way we do most calls to the database, but somehow this query is not working.
--EDIT
By request This Is the SQL that is placed within the QueryDef.
SELECT IIf([Brand]='Somebrand','SO',IIf(left([Brand],6)='SomeOtherBrand',IIf(CHARINDEX('168/2013', [WVTA])=0,'FOOBAR','BARFOO'),IIf([Brand]='Anotherbrand','BAR',IIf([Brand]='YetAnotherBrand','Foo','ander')))) AS Company,
qtmpgetVINApprovalData.VIN, qtmpgetVINApprovalData.WVTA, qtmpgetVINApprovalData.Variant, qtmpgetVINApprovalData.Version, qtmpgetVINApprovalData.NKS, qtmpgetVINApprovalData.productionDate AS Production,
qtmpgetVINApprovalData.color, qtmpgetVINApprovalData.actualMass, qtmpgetVINApprovalData.NKS_YYYY,qtmpgetVINApprovalData.NKS_SSSS, '' AS engine, qtmpgetVINApprovalData.EmisTestMassWLTP,
qtmpgetVINApprovalData.FrontalAreaWLTP, qtmpgetVINApprovalData.RoadLoadCoefF0WLTP, qtmpgetVINApprovalData.RoadLoadCoefF1WLTP, qtmpgetVINApprovalData.RoadLoadCoefF2WLTP,
qtmpgetVINApprovalData.WLTPCOMBINED_REPORTING_CO2 AS CombinedCo2ConditionA, qtmpgetVINApprovalData.WLTPCOMBINED_REPORTING_CO2 AS CombinedCo2ConditionB,
qtmpgetVINApprovalData.WLTPCOMBINED_REPORTING_FC AS CombinedFuelConsConditionA, qtmpgetVINApprovalData.WLTPCOMBINED_REPORTING_FC AS CombinedFuelConsConditionB,
qtmpgetVINApprovalData.OVCEnergyConsPureElectric AS ElectricEnergyConsConditionA, qtmpgetVINApprovalData.OVCEnergyConsPureElectric AS ElectricEnergyConsConditionB,
qtmpgetVINApprovalData.ElectricEnergyConsPureElectric , qtmpgetVINApprovalData.ElectricRange, OVCEnergyConsPureElectric, OVCRange, OVCRangeCity,
qtmpgetVINApprovalData.OVCRange AS ElectricRangeExternChargeable, qtmpgetVINApprovalData.WLTPLowCO2, qtmpgetVINApprovalData.WLTPMediumCO2, qtmpgetVINApprovalData.WLTPHighCO2,
qtmpgetVINApprovalData.WLTPExtraHighCO2, qtmpgetVINApprovalData.WLTPCombinedCO2, qtmpgetVINApprovalData.WLTPWeightedCombinedCO2, qtmpgetVINApprovalData.WLTPLowFuelConsumption,
qtmpgetVINApprovalData.WLTPMediumFuelConsumption, qtmpgetVINApprovalData.WLTPHighFuelConsumption, qtmpgetVINApprovalData.WLTPExtraHighFuelConsumption,
qtmpgetVINApprovalData.WLTPCombinedFuelCons, qtmpgetVINApprovalData.WLTPWeightedCombinedFuelCons, 0 as WltpElecEnergyConsPureElectric,0 as WltpElectricRangePureElectric,
0 as WltpElectricRangeCityPureElec,0 as WltpElectEnergyConsExternCharg, 0 as WltpElectricRangeExternCharg,0 as WltpElectricRangeCityExtCharg, qtmpgetVINApprovalData.EMISSIONSTAGE,
colorahosid, UrbanConditionsCO2, UrbanConditionsFuelConsumption, ExtraUrbanConditionsCO2, ExtraUrbanConditionsFuelCons, CombinedCO2, CombinedConditionsFC, WeightedCombinedCO2,
WeightedCombinedFuelCons, ElectricEnergyConsWeightedComb, ElectricRangeNEDC, ElectricRangeCity FROM (SELECT DISTINCT
CASE WHEN isnull(WLTPLowFuelConsumption,0)>15
THEN 'Error: Fuel consumption value too high'
ELSE
CASE WHEN isnull(WLTPMediumCO2,0)>800
THEN 'Error: WLTP Medium CO2 value too high'
ELSE
case when isnull(RoadLoadCoefF1WLTP,0)>1000
THEN 'Error: RoadLoadCoeff too high'
ELSE
case when isnull(qvtvv.tvvid,0)=0
THEN 'ERROR: TVV (PCOC) data missing'
ELSE
case when isnull(qvtvv.eurolevel,'X')='X'
THEN 'ERROR: EmissionLegislation Missing'
ELSE
CASE when isnull(cocVINList.prodDate,'1900-01-01')='1900-01-01'
THEN 'ERROR: Production Date Missing'
ELSE
CASE when isnull(qvTVV.colorAHOSID,999)=999
THEN 'ERROR: Color missing'
ELSE
CASE when isnull(nkstvv.wvta,'X')='X'
then --NKS
case when isnull(nkstvv.wvta,'X')='X'
then --NKS
case when isnull(dbo.cocVINList.[actualMass],0)=0
THEN 'ERROR: Actual Mass missing'
else 'OK'
END
else --BASE VEH
case when isnull(NKS_PCOC.NKS_MassRunningOrder,0)=0
THEN 'ERROR: Actual Mass missing'
else 'OK'
END
end
ELSE
case when [WVTACOCLayoutVersions].description like '%2018%WLTP%'
THEN
case when isnull(EmisTestMassWLTP,0)=0
THEN 'ERROR: WLTP data missing'
else 'OK'
end
ELSE 'OK'
END
END
END
END
END
END
END
END
END
as VALIDATION,
dbo.cocVINList.VIN,
dbo.cocVINList.NKS,
case when isnull(nkstvv.wvta,'X')='X' then dbo.qvTVV.WVTA else nkstvv.wvta end as WVTA,
case when isnull(nkstvv.Variant,'X')='X' then dbo.qvTVV.Variant else nkstvv.Variant end as Variant,
case when isnull(nkstvv.Version,'X')='X' then dbo.qvTVV.Version else nkstvv.Version end as Version,
case when isnull(nkstvv.wvta,'X')='X' then dbo.cocVINList.[actualMass] else NKS_PCOC.NKS_MassRunningOrder end as actualMass,
case when isnull(nkstvv.wvta,'X')='X' then cocVINList.prodDate else NKS_PCOC.COC_Datum end as productionDate,
case when isnull(nkstvv.wvta,'X')='X' then dbo.qvTVV.wvtadate else nkstvv.wvtadate end as WVTADate,
qvTVV.color, qvTVV.colorAHOSID,
qvTVV.Type_watermark_paper as Brand,
case when isnull(nkstvv.wvta,'X')<>'X' THEN
case when charindex('2007/46',nkstvv.wvta)= 0 then qvtvv.NKS_YYYY END
END as NKS_YYYY,
case when isnull(nkstvv.wvta,'X')<>'X' THEN
case when charindex('2007/46',nkstvv.wvta)= 0 then qvTVV.NKS_SSSS END
END as NKS_SSSS,
[EmisTestMassWLTP],
[FrontalAreaWLTP],
[RoadLoadCoefF0WLTP],
[RoadLoadCoefF1WLTP],
[RoadLoadCoefF2WLTP],
[CombinedConditionsCO2],
[CombinedConditionsFC],
[OVCEnergyConsPureElectric],
[OVCRange],
[OVCRangeCity],
[ElectricEnergyConsPureElectric],
[ElectricRange],
ElectricRangeCity,
[WLTPLowCO2],
[WLTPMediumCO2],
[WLTPHighCO2],
[WLTPExtraHighCO2],
[WLTPCombinedCO2],
[WLTPWeightedCombinedCO2],
[WLTPLowFuelConsumption],
[WLTPMediumFuelConsumption],
[WLTPHighFuelConsumption],
[WLTPExtraHighFuelConsumption],
[WLTPCombinedFuelCons],
[WLTPWeightedCombinedFuelCons],
ElectricEnergyConsWeightedComb,ElectricRangeNEDC,
UrbanConditionsCO2,
ExtraUrbanConditionsCO2,
CombinedConditionsCO2 as CombinedCO2,
UrbanConditionsFuelConsumption,
ExtraUrbanConditionsFuelCons,
WeightedCombinedCO2,
WeightedCombinedFuelCons,
case when [WLTPCombinedFuelCons]=0
THEN
CASE WHEN WLTPWeightedCombinedFuelCons=0
THEN NULL
ELSE WLTPWeightedCombinedFuelCons
END
ELSE [WLTPCombinedFuelCons]
END AS WLTPCOMBINED_REPORTING_FC ,
case when [WLTPCombinedCO2]=0
THEN
CASE WHEN WLTPWeightedCombinedCO2=0
THEN NULL
ELSE WLTPWeightedCombinedCO2
END
ELSE [WLTPCombinedCO2]
END AS WLTPCOMBINED_REPORTING_CO2,
case when isnull(EmisTestMassWLTP,0)>0
THEN 'WLTP'
else
case when [WVTACOCLayoutVersions].description like '%2018%WLTP%'
THEN 'WLTP'
ELSE 'NEDC'
END
END AS EMISSIONSTAGE,
qvtvv.EmissionLegislation , qvTVV.fname
FROM dbo.qvTVV
inner join cocvinlist on qvTVV.vin=cocvinlist.vin
left join qvtvvshort NKSTVV on nkstvvid=nkstvv.tvvid
left join [WVTATVV] on [WVTATVV].tvvid=qvtvv.tvvid
left join [WVTACOCLayoutVersions]
on [VersionNr]=case when isnull(nkstvv.cat,'X')='X'
then dbo.qvTVV.LayoutVersion
else nkstvv.LayoutVersion
end
and [WVTACOCLayoutVersions].cat=case when isnull(nkstvv.cat,'X')='X'
then left(dbo.qvTVV.cat+' ',2)
else left(nkstvv.cat+' ',2)
end
and [WVTACOCLayoutVersions].completion=case when isnull(nkstvv.cat,'X')='X'
then dbo.qvTVV.completion
else nkstvv.completion
end
left join NKS_PCOC on NKS_PCOC.VIN=qvTVV.VIN
WHERE
dbo.cocVINList.vin in (select VIN from codap_exportvins where cuser ='USER.NAME')
and case when [WVTACOCLayoutVersions].description like '%2018%WLTP%' then case when [EmisTestMassWLTP]=0 then 0 else 1 end else 1 end=1) as qtmpgetVINApprovalData where validation ='OK';

Essentially, you are conflating SQL dialects. Using DAO's Database.OpenRecordset calls the Access engine which can only read MS Access SQL dialect (not SQL Server). This action will fail on dbo., CASE, CHARINDEX, and others.
Instead, consider as #ErikA comments to use the QueryDef.OpenRecordset underlying recordset which will decide which backend SQL engine to run:
Dim qdef As QueryDef
Set qdef = DB.QueryDefs("qryName")
Set rsNew = qdef.OpenRecordset(dbSeeChanges)
...
Further reading: SQL Server Passthrough query as basis for a DAO recordset in Access
.

Related

VBA Select case 1 to 100 only taking 1

I'm trying to make a select case that identifies if a number is lower than 0, 1 to 100 or greater than 100, the thing is that is just doesn't work. Here's my code:
If IsNumeric(TxtTemp.Text) Then
Select Case TxtTemp.Text
Case Is <= 0
TxtEstado.Text = "Solid"
Case 1 To 100
TxtEstado.Text = "Liquid"
Case Is > 100
TxtEstado.Text = "Gas"
End Select
Else
TxtEstado.Text = ""
End If
I know that this is an easy thing to do, the thing is that the select case returns liquid only if the number received is equal to 1. If it is lower or equal to 0 it returns solid, but if it is equal or greater to 2, it returns gas. I don't understand what I'm doing wrong.
Maybe it is easier to use a function for this kind of conversion
Function chText(txt As String) As String
On Error GoTo EH
Dim resTxt As String
If IsNumeric(txt) Then
Select Case CDbl(txt)
Case Is <= 0
resTxt = "Solid"
Case 1 To 100
resTxt = "Liquid"
Case Is > 100
resTxt = "Gas"
End Select
Else
resTxt = ""
End If
chText = resTxt
Exit Function
EH:
chText = "Error"
End Function
Sub Tester()
Debug.Print chText("101")
' TxtEstado.Text = chText(TxtTemp.Text)
End Sub

How to compare two dates in text boxes?

I want to compare two dates in text boxes.
Public Function CourseStatus(ByVal RefDate2 As Variant) As String
Dim Description As String
If Len(RefDate2) > 0 And IsDate(RefDate2) Then
Select Case DateDiff("d", Date, RefDate2)
Case Is > 60
CourseStatus = "In Date"
Case Is > 0
CourseStatus = "Expiring"
Case Is = [ParticipationDate]
CourseStatus = "Not Refreshed"
Case Else
CourseStatus = "Expired"
End Select
Else
CourseStatus = "Please Book"
End If
End Function
If [ParticipationDate] & [RefDate2] match return "Not Refreshed" as CourseStatus.
I need to do this before running the rest of the code to give "in Date" "Expiring" "Expired" and if none of this applies display "Please Book".
e.g
ParticipationDate 1/1/19
RefDate2 1/1/19
CourseStatus "Not Refreshed"
Sorry I didn't read your code super accurately.
Your datediff function returns a integer value not a date. You should use
Case is 0
to check for a date match.
You might use something like this:
If Len(RefDate2) > 0 And IsDate(RefDate2) Then
Select Case DateDiff("d", Date, RefDate2)
Case Is > 60
CourseStatus = "In Date"
Case Is > 0
CourseStatus = "Expiring"
Case Else
If DateDiff("d", RefDate2, [ParticipationDate]) = 0 Then
CourseStatus = "Not Refreshed"
Else
CourseStatus = "Expired"
End If
End Select
Else
CourseStatus = "Please Book"
End If

Converting VB conditions to SQL conditions

There are some VB conditions that I need to execute in SQL query. Is this possible? Here's the code:::::::::::::::::::::::::::::::::::::::::::::::
If (ds.Tables(0).Rows.Count > 0) Then
Dim timeIn = ds.Tables(0).Rows(0)("TimeIn").ToString
Dim timeOut = ds.Tables(0).Rows(0)("TimeOut").ToString
If Not String.IsNullOrEmpty(timeIn) And Not String.IsNullOrEmpty(timeOut) Then
Dim result = DateTime.Compare(Convert.ToDateTime(timeIn), Convert.ToDateTime(timeOut))
If result > 0 Then 'last timeIn later than last timeOut
attendanceStatus = "On"
Else
attendanceStatus = "Off"
End If
ElseIf Not String.IsNullOrEmpty(timeIn) And String.IsNullOrEmpty(timeOut) Then
attendanceStatus = "On"
End If
lblAttendStatus.Text = attendanceStatus
End If
End If
You can do that by including in your SQL statement after SELECT:
CASE WHEN TimeIn < TimeOut THEN 'Off' ELSE 'On' END AS attendanceStatus,

Query Timeout Expired in SSAS Cube Processing

While migrating a cube from 2008 to 2014, we had a cube processing failure with the message "Query Timeout Expired : HYT00". I looked into the error information and found a certain query executing for more than an hour which is causing the issue. The query is,
SELECT [dbo_IndicatorFact].[PY] AS [dbo_IndicatorFactPY0_0],[dbo_IndicatorFact].[BP] AS [dbo_IndicatorFactBP0_1],[dbo_IndicatorFact].[RE] AS [dbo_IndicatorFactRE0_2],[dbo_IndicatorFact].[UCPY] AS [dbo_IndicatorFactUCPY0_3],[dbo_IndicatorFact].[UCBP] AS [dbo_IndicatorFactUCBP0_4],[dbo_IndicatorFact].[UCRE] AS [dbo_IndicatorFactUCRE0_5],[dbo_IndicatorFact].[GRPY] AS [dbo_IndicatorFactGRPY0_6],[dbo_IndicatorFact].[GRBP] AS [dbo_IndicatorFactGRBP0_7],[dbo_IndicatorFact].[GRRE] AS [dbo_IndicatorFactGRRE0_8],[dbo_IndicatorFact].[NRPY] AS [dbo_IndicatorFactNRPY0_9],[dbo_IndicatorFact].[NRBP] AS [dbo_IndicatorFactNRBP0_10],[dbo_IndicatorFact].[NRRE] AS [dbo_IndicatorFactNRRE0_11],[dbo_IndicatorFact].[GRC2] AS [dbo_IndicatorFactGRC20_12],[dbo_IndicatorFact].[AnalysisCategoryId] AS [dbo_IndicatorFactAnalysisCategoryId0_13],[dbo_IndicatorFact].[IndicatorTypeId] AS [dbo_IndicatorFactIndicatorTypeId0_14],[dbo_IndicatorFact].[IndicatorNameId] AS [dbo_IndicatorFactIndicatorNameId0_15],[dbo_IndicatorFact].[CategoryId] AS [dbo_IndicatorFactCategoryId0_16],[dbo_IndicatorFact].[CountryId] AS [dbo_IndicatorFactCountryId0_17],[dbo_IndicatorFact].[FiscalQuarterId] AS [dbo_IndicatorFactFiscalQuarterId0_18]
FROM
(
SELECT vwIndicatorFact.IndicatorId AS Id,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN vwIndicatorFact.PY ELSE CASE IndicatorFact_GRC2.PY WHEN 0 THEN 0 ELSE vwIndicatorFact.PY END END AS PY,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN vwIndicatorFact.BP ELSE CASE IndicatorFact_GRC2.BP WHEN 0 THEN 0 ELSE vwIndicatorFact.BP END END AS BP,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN vwIndicatorFact.RE ELSE CASE IndicatorFact_GRC2.RE WHEN 0 THEN 0 ELSE vwIndicatorFact.RE END END AS RE,
vwIndicatorFact.BPvsPY, vwIndicatorFact.BPvsPYpercent, vwIndicatorFact.REvsBP, vwIndicatorFact.REvsBPpercent, vwIndicatorFact.REvsPY,
vwIndicatorFact.REvsPYpercent,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN CASE vwIndicatorFact.IndicatorNameId WHEN 1 THEN 1000000 ELSE IndicatorFact_UC.PY END ELSE CASE IndicatorFact_GRC2.PY
WHEN 0 THEN 0 ELSE CASE vwIndicatorFact.IndicatorNameId WHEN 1 THEN 1000000 ELSE IndicatorFact_UC.PY END END END AS UCPY,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN CASE vwIndicatorFact.IndicatorNameId WHEN 1 THEN 1000000 ELSE IndicatorFact_UC.BP END ELSE CASE IndicatorFact_GRC2.BP
WHEN 0 THEN 0 ELSE CASE vwIndicatorFact.IndicatorNameId WHEN 1 THEN 1000000 ELSE IndicatorFact_UC.BP END END END AS UCBP,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN CASE vwIndicatorFact.IndicatorNameId WHEN 1 THEN 1000000 ELSE IndicatorFact_UC.RE END ELSE CASE IndicatorFact_GRC2.RE
WHEN 0 THEN 0 ELSE CASE vwIndicatorFact.IndicatorNameId WHEN 1 THEN 1000000 ELSE IndicatorFact_UC.RE END END END AS UCRE, vwIndicatorFact.IndicatorNameId,
vwIndicatorFact.CategoryId, vwIndicatorFact.AnalysisCategoryId, vwIndicatorFact.CountryId, vwIndicatorFact.FiscalQuarterId, vwIndicatorFact.IndicatorTypeId,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN IndicatorFact_GR.PY ELSE CASE IndicatorFact_GRC2.PY WHEN 0 THEN 0 ELSE IndicatorFact_GR.PY END END AS GRPY,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN IndicatorFact_GR.BP ELSE CASE IndicatorFact_GRC2.BP WHEN 0 THEN 0 ELSE IndicatorFact_GR.BP END END AS GRBP,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN IndicatorFact_GR.RE ELSE CASE IndicatorFact_GRC2.RE WHEN 0 THEN 0 ELSE IndicatorFact_GR.RE END END AS GRRE,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN IndicatorFact_NR.PY ELSE CASE IndicatorFact_GRC2.PY WHEN 0 THEN 0 ELSE IndicatorFact_NR.PY END END AS NRPY,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN IndicatorFact_NR.BP ELSE CASE IndicatorFact_GRC2.BP WHEN 0 THEN 0 ELSE IndicatorFact_NR.BP END END AS NRBP,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN IndicatorFact_NR.RE ELSE CASE IndicatorFact_GRC2.RE WHEN 0 THEN 0 ELSE IndicatorFact_NR.RE END END AS NRRE,
IndicatorFact_GRC2.BP AS GRC2
FROM
dbo.vwIndicatorFact INNER JOIN
dbo.vwIndicatorFact AS IndicatorFact_UC ON vwIndicatorFact.IndicatorTypeId = IndicatorFact_UC.IndicatorTypeId AND
vwIndicatorFact.FiscalQuarterId = IndicatorFact_UC.FiscalQuarterId AND vwIndicatorFact.CountryId = IndicatorFact_UC.CountryId AND
vwIndicatorFact.CategoryId = IndicatorFact_UC.CategoryId AND IndicatorFact_UC.IndicatorNameId = 1 LEFT OUTER JOIN
dbo.vwIndicatorFact AS IndicatorFact_GR ON vwIndicatorFact.IndicatorTypeId = IndicatorFact_GR.IndicatorTypeId AND
vwIndicatorFact.FiscalQuarterId = IndicatorFact_GR.FiscalQuarterId AND vwIndicatorFact.CountryId = IndicatorFact_GR.CountryId AND
vwIndicatorFact.CategoryId = IndicatorFact_GR.CategoryId AND IndicatorFact_GR.IndicatorNameId = 3 AND
IndicatorFact_GR.AnalysisCategoryId = vwIndicatorFact.AnalysisCategoryId LEFT OUTER JOIN
dbo.vwIndicatorFact AS IndicatorFact_NR ON vwIndicatorFact.IndicatorTypeId = IndicatorFact_NR.IndicatorTypeId AND
vwIndicatorFact.FiscalQuarterId = IndicatorFact_NR.FiscalQuarterId AND vwIndicatorFact.CountryId = IndicatorFact_NR.CountryId AND
vwIndicatorFact.CategoryId = IndicatorFact_NR.CategoryId AND IndicatorFact_NR.IndicatorNameId = 5 AND
IndicatorFact_NR.AnalysisCategoryId = vwIndicatorFact.AnalysisCategoryId LEFT OUTER JOIN
dbo.vwIndicatorFact AS IndicatorFact_GRC2 ON IndicatorFact_GRC2.IndicatorTypeId = 2 AND vwIndicatorFact.FiscalQuarterId = IndicatorFact_GRC2.FiscalQuarterId AND
vwIndicatorFact.CountryId = IndicatorFact_GRC2.CountryId AND vwIndicatorFact.CategoryId = IndicatorFact_GRC2.CategoryId AND
IndicatorFact_GRC2.IndicatorNameId = 3 AND IndicatorFact_GRC2.AnalysisCategoryId = 2
)
AS [dbo_IndicatorFact]
This is basically multiple self joins on a particular view which contains 300k records. Our dba updated all the indexes and updated the stats, But we are still not able to execute this query quickly. If this query executes quicker, there's a chance that the cube will process quicker. The data in the view also has no inconsistencies. Need some advice on what could be the issue here.
Some background on this - this is part of migration project that we are working on. The old dev environment is able to execute the same query in about 20 seconds with similar number of records in the view. The new dev takes forever to execute the same query with the same view.
In your statement it can be anything: poor indexes, outdated statistics, bad statement, huge data....
I had similar problem and I've increased external command timeout in SSAS(it is 1 hour by default). Look here how to do it if you will not manage to optimize your query:
http://www.msbiguide.com/2013/01/how-to-increase-externalcommandtimeout-in-ssas/

SQL / VB.NET - Query doesn't return to application

I've got a MSSQL procedure running fine from the SQL Management console, but when I try to run it from my VB.NET it simply never returns. Someone have any idea?
I am testing with the same database.
SQL CODE (PROCEDURE)
ALTER PROCEDURE [dbo].[P_DEN_L_IMPRESSAO_ORCAMENTOS_APROVADO_NOVO]
(
#PAC_D_DATA_INICIAL DATETIME = NULL,
#PAC_D_DATA_FINAL DATETIME = NULL,
#PAC_DET_N_CODIGO DECIMAL = NULL,
#PAC_CLI_N_CODIGO DECIMAL = NULL,
#PAC_EMP_N_CODIGO DECIMAL = NULL
)
AS
SELECT
PAC_N_CODIGO,
PAC_C_CODIGO_INTERNO,
PAC_C_NOME,
PAC_C_EMAIL,
PAC_C_TELEFONE_RES,
PAC_CLI_N_CODIGO,
CLI_C_DESCRICAO,
ODO_D_DATA_INICIO,
ODO_D_DATA_FINAL,
ODO_PTR_N_CODIGO,
CASE PAC_N_CORRESPONDENCIA
WHEN 1 THEN
PAC_C_ENDERECO_RES +
CASE
WHEN PAC_C_NUMERO_RES IS NULL OR PAC_C_NUMERO_RES = '' THEN ''
ELSE ', ' + PAC_C_NUMERO_RES
END +
CASE
WHEN PAC_C_COMPLEMENTO_RES IS NULL OR PAC_C_COMPLEMENTO_RES = '' THEN ''
ELSE ', ' + PAC_C_COMPLEMENTO_RES
END
WHEN 2 THEN
PAC_C_ENDERECO_COM +
CASE
WHEN PAC_C_NUMERO_COM IS NULL OR PAC_C_NUMERO_COM = '' THEN ''
ELSE ', ' + PAC_C_NUMERO_COM
END +
CASE
WHEN PAC_C_COMPLEMENTO_COM IS NULL OR PAC_C_COMPLEMENTO_COM = '' THEN ''
ELSE ', ' + PAC_C_COMPLEMENTO_COM
END
END AS PAC_C_ENDERECO,
CASE PAC_N_CORRESPONDENCIA
WHEN 1 THEN PAC_C_BAIRRO_RES
WHEN 2 THEN PAC_C_BAIRRO_COM
END AS PAC_C_BAIRRO,
CASE PAC_N_CORRESPONDENCIA
WHEN 1 THEN PAC_C_CIDADE_RES
WHEN 2 THEN PAC_C_CIDADE_COM
END AS PAC_C_CIDADE,
CASE PAC_N_CORRESPONDENCIA
WHEN 1 THEN
(SELECT EST_C_RESUMIDO
FROM DEN_EST_ESTADO
WHERE EST_N_CODIGO = PAC_EST_N_CODIGO_RES)
WHEN 2 THEN
(SELECT EST_C_RESUMIDO
FROM DEN_EST_ESTADO
WHERE EST_N_CODIGO = PAC_EST_N_CODIGO_COM)
END AS EST_C_RESUMIDO,
CASE PAC_N_CORRESPONDENCIA
WHEN 1 THEN PAC_C_CEP_RES
WHEN 2 THEN PAC_C_CEP_COM
END AS PAC_C_CEP,
ODO_N_VERSAO,
PAC_C_CELULAR,
PAC_DET_N_CODIGO,
ODO_N_CODIGO,
SUM(VIN_N_VALOR) as 'T_PROC',
(SELECT SUM(VIN_N_VALOR) FROM DEN_VIN_VINCULO_TRATAMENTO
WHERE VIN_OXD_ODO_N_CODIGO = ODO_N_CODIGO) as 'VIN_N_VALOR',
convert(decimal(18,2),0) AS 'T_ENTRADA'
FROM
DEN_PAC_PACIENTE
INNER JOIN
DEN_DET_DENTISTA
ON
DET_N_CODIGO = PAC_DET_N_CODIGO
AND
DET_CLI_N_CODIGO = PAC_CLI_N_CODIGO
INNER JOIN
DEN_CLI_CLINICA
ON
CLI_N_CODIGO = PAC_CLI_N_CODIGO
INNER JOIN
DEN_EMP_EMPRESA
ON
EMP_N_CODIGO = CLI_EMP_N_CODIGO
INNER JOIN
DEN_ODO_ODONTOGRAMA
ON
ODO_PAC_N_CODIGO = PAC_N_CODIGO
INNER JOIN
DEN_VIN_VINCULO_TRATAMENTO
ON
VIN_OXD_ODO_N_CODIGO = ODO_N_CODIGO
WHERE
(ODO_D_DATA_FINAL BETWEEN #PAC_D_DATA_INICIAL AND #PAC_D_DATA_FINAL)
AND
(ODO_PTR_N_CODIGO = 2)
AND
(ODO_B_APROVADO = 1)
AND
(#PAC_CLI_N_CODIGO IS NULL OR PAC_CLI_N_CODIGO = #PAC_CLI_N_CODIGO)
AND
(#PAC_DET_N_CODIGO IS NULL OR VIN_DET_N_CODIGO = #PAC_DET_N_CODIGO)
AND
(CLI_EMP_N_CODIGO = #PAC_EMP_N_CODIGO)
AND
(PAC_B_ATIVO = 1)
AND
(PAC_B_POTENCIAL = 0)
GROUP BY
PAC_N_CODIGO,
PAC_C_CODIGO_INTERNO,
PAC_C_NOME,
PAC_C_EMAIL,
PAC_C_TELEFONE_RES,
PAC_CLI_N_CODIGO,
CLI_C_DESCRICAO,
ODO_D_DATA_INICIO,
ODO_D_DATA_FINAL,
ODO_PTR_N_CODIGO,
ODO_N_VERSAO,
PAC_C_CELULAR,
PAC_DET_N_CODIGO,
ODO_N_CODIGO,
PAC_N_CORRESPONDENCIA,
PAC_C_ENDERECO_RES,
PAC_C_NUMERO_RES,
PAC_C_NUMERO_RES,
PAC_C_COMPLEMENTO_RES,
PAC_C_ENDERECO_COM,
PAC_C_NUMERO_COM,
PAC_C_COMPLEMENTO_COM,
PAC_C_BAIRRO_RES,
PAC_C_BAIRRO_COM,
PAC_C_CIDADE_RES,
PAC_C_CIDADE_COM,
PAC_EST_N_CODIGO_RES,
PAC_EST_N_CODIGO_COM,
PAC_C_CEP_RES,
PAC_C_CEP_COM
ORDER BY
PAC_C_NOME, ODO_N_VERSAO
VB.NET CODE
Public Function ListarOrcamentosAprovadoNovo(ByVal mdlPaciente As Paciente, _
ByVal datDataInicial As Date, _
ByVal datDataFinal As Date, _
ByVal pblnEtiqueta As Boolean, Optional ByVal pstrCodigos As String = "") As DataTable
Try
cmdCommand = New FWCommand
With cmdCommand
.CommandText = "P_DEN_L_IMPRESSAO_ORCAMENTOS_APROVADO_NOVO"
.CommandTimeout = intCommandTimeOut
.CommandType = CommandType.StoredProcedure
.Parameters.Add(New FWParameter("#PAC_D_DATA_INICIAL", FWDbType.DateTime))
.Parameters("#PAC_D_DATA_INICIAL").Value = datDataInicial
.Parameters.Add(New FWParameter("#PAC_D_DATA_FINAL", FWDbType.DateTime))
.Parameters("#PAC_D_DATA_FINAL").Value = datDataFinal
If mdlPaciente.CodDentista > -1 Then
.Parameters.Add(New FWParameter("#PAC_DET_N_CODIGO", FWDbType.Decimal))
.Parameters("#PAC_DET_N_CODIGO").Value = mdlPaciente.CodDentista
End If
If mdlPaciente.CodClinica > 0 Then
.Parameters.Add(New FWParameter("#PAC_CLI_N_CODIGO", FWDbType.Decimal))
.Parameters("#PAC_CLI_N_CODIGO").Value = mdlPaciente.CodClinica
End If
If mdlPaciente.CodEmpresa > 0 Then
.Parameters.Add(New FWParameter("#PAC_EMP_N_CODIGO", FWDbType.Decimal))
.Parameters("#PAC_EMP_N_CODIGO").Value = mdlPaciente.CodEmpresa
End If
End With
Return conProvider.ExecuteDataTable(cmdCommand)
Catch ex As Exception
Throw
Finally
cmdCommand = Nothing
End Try
End Function
Things to check:
Check that your .NET connection string is pointing to the same database that
you are using in your SSMS query
You are using different parameter values in you .NET code then when running in SSMS
This could be related to "parameter sniffing". Possible workarounds are
a) adding with(recompile) to the proc,
b) add a set of local variables that you copy the parameter values into and use the local variables in the query,
c) use OPTION (OPTIMIZE FOR (#VARIABLE UNKNOWN)), or
d) trace flag 4136 that can be used to disable the "parameter sniffing" process (http://support.microsoft.com/kb/980653)
See these articles for more details on parameter sniffing:
http://blogs.msdn.com/b/turgays/archive/2013/09/10/parameter-sniffing-problem-and-workarounds.aspx
http://blogs.technet.com/b/mdegre/archive/2012/03/19/what-is-parameter-sniffing.aspx