Converting VB conditions to SQL conditions - sql

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,

Related

How to fix 'ODCB call failed during OpenRecordSet'

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
.

Is Null return ""

I have the following code however if the RefDate is blank it is returning #Type!. Can I add in a line to say ifNull = ""
Public Function Status(ByVal RefDate As Date) As String
Dim Description As String
Select Case DateDiff("d", Date, RefDate)
Case > 60
Description = "In date"
Case > 0
Description = "Expiring"
Case Else
Description = "Expired"
End Select
Status = Description
End Function
If Null return "" nothing or blank
Try this, I've changed the input data type also
Public Function Status(ByVal RefDate As Variant) As String
Dim Description As String
If Len(RefDate) > 0 and IsDate(RefDate) Then
Select Case DateDiff("d", Date, RefDate)
Case Is > 60
Status = "In date"
Case Is > 0
Status = "Expiring"
Case Else
Status = "Expired"
End Select
Else
Status = "No date"
End If
End Function
Trying a similar approach, when comparing with #Ryan Wildry, but now explicitly setting "" to Description
Public Function Status(ByVal RefDate As Date) As String
Dim Description As String
If CInt(RefDate) = 0 Then
Description = ""
Else
Select Case DateDiff("d", Date, RefDate)
Case Is > 60
Description = "In date"
Case Is > 0
Description = "Expiring"
Case Else
Description = "Expired"
End Select
End If
Status = Description
End Function

Changing VBA code - into - SQL statement

I have this code in Excel VBA:
If Cells(lngRow, ConstTASTMS_ActivateTime).Value < getdate() - 7 Then
Cells(lngRow, ConstTASTimeClass).Value = "BOH"
If Cells(lngRow, ConstTASTask_Status) = "Closed" Then
If Cells(lngRow, ConstTASActual_EndDate).Value <= getdate() - 7 Then
Cells(lngRow, ConstTASTimeClass).Value = "BOH-CO"
Else
Cells(lngRow, ConstTASTimeClass).Value = "BOH-C"
End If
End If
If Cells(lngRow, ConstTASTask_StatusReason) = "Canceled" Then
If Cells(lngRow, ConstTASActual_EndDate).Value <= getdate() Then
Cells(lngRow, ConstTASTimeClass).Value = "BOH-XO"
Else
Cells(lngRow, ConstTASTimeClass).Value = "BOH-X"
End If
End If
Else
Cells(lngRow, ConstTASTimeClass).Value = "New"
If Cells(lngRow, ConstTASTask_Status) = "Closed" Then Cells(lngRow, ConstTASTimeClass).Value = "New-C"
If Cells(lngRow, ConstTASTask_Status) = "Canceled" Then Cells(lngRow, ConstTASTimeClass).Value = "New-X"
End If
And now, I need to translate it into the SQL statement.
So far, I got this, and don't think it's correct.
Can someone please take a look and help me to correct it?
CASE WHEN TMS_ActivateTime < getdate() - 7 THEN
TimeClass = "BOH"
CASE WHEN Task_Status = "Closed" THEN
CASE WHEN Actual_EndDate <= getdate() - 7 THEN
TimeClass = "BOH-CO"
ELSE
TimeClass = "BOH-C"
CASE WHEN Task_StatusReason = "Canceled" THEN
CASE WHEN Actual_EndDate <= getdate() THEN
TimeClass = "BOH-XO"
ELSE
TimeClass = "BOH-X"
ELSE
TimeClass = "New"
CASE WHEN Task_Status = "Closed" THEN TimeClass = "New-C"
CASE WHEN Task_Status = "Canceled" THEN TimeClass = "New-X"
END
I'll give it a shot. As the CASE will not evaluate any further after a WHEN is true, we need to sometimes reverse the order in which the values are assigned to TimeClass.
SELECT
CASE WHEN TMS_ActivateTime < getdate() - 7 THEN
CASE WHEN Task_StatusReason = "Canceled" THEN
CASE WHEN Actual_EndDate <= getdate() THEN
'BOH-XO'
ELSE 'BOH-X'
END
WHEN Task_Status = 'Closed' THEN
CASE WHEN Actual_EndDate <= getdate() - 7 THEN
'BOH-CO'
ELSE 'BOH-C'
END
ELSE 'BOH'
END
ELSE
CASE
WHEN TaskStatus = 'Canceled' THEN 'New-X'
WHEN TaskStatus = 'Closed' THEN 'New-C'
ELSE 'New' END
END
AS TimeClass
While it is not necessary in SQL syntax, it is helpful to format your case statements to see where a field ends and begins, i.e.:
--Field 1
CASE
WHEN
THEN
ELSE
END
--Field 2
CASE
WHEN
THEN
CASE
--still Field 2
WHEN
THEN
END
END

SQL Server : IF Condition in WHERE clause

I have a bit parameter
#IsInRetry
If it is false I have to set the where condition to
attempts = 0
else if it is true I have to set the where condition to
attempts > 0
How could this be done?
Try this way:
( (#IsInRetry = 0 and attempts = 0) or (#IsInRetry = 1 and attempts > 0) )
Try this:
WHERE (attempts = #IsInRetry or (#IsInRetry = 1 and attempts > 0))
Try this, should work also for negative attempts :-)
#IsInRetry = (attempts > 0)
Greetings.
This:
if #IsInRetry = 0x0
BEGIN
SELECT * FROM dbo.tbl
WHERE attempts = 0
END
ELSE
BEGIN
SELECT * FROM dbo.tbl
WHERE attempts = 1
END

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