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

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

Related

'System.ArgumentOutOfRangeException'"Tried the other solution but never gotten to the point of resolving" [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 2 years ago.
i've tried the other solution(like changing item that should be shown on data) but i think i've never gotten the point to resolving. Thank you in advance whoever can answer my problem...
Private Sub dgEmp_Click(sender As Object, e As EventArgs) Handles dgEmp.Click
LoadEmployeeInfo(dgEmp.SelectedRows.Item(0).Index)
End Sub
Private Sub LoadEmployee(Optional q As String = "")
list.Query = "Select id,lastname,firstname,middlename,sss,philh,pag,rate,cola,mStatus,free_insurance,mp,mpvalue from tblemployee where (lastname like'%" & q & "%' or firstname like'%" & q & "%' or middlename like'%" & q & "%') and deactive='No' order by lastname,firstname,middlename"
list.datagrid = dgEmp
list.LoadRecords()
If list.RecordCount = Nothing Then Exit Sub
LoadEmployeeInfo(dgEmp.SelectedRows.Item(0).Index)
End Sub
Public Sub LoadEmployeeInfo(index As Integer)
With dgEmp.Rows(index)
id = .Cells(0).Value
lblName.Text = .Cells(1).Value & ", " & .Cells(2).Value & " " & .Cells(3).Value
rpd = .Cells(7).Value
lblRate.Text = Format(rpd, "#,##0.000000000")
cola = .Cells(8).Value
lblAllo.Text = Format(cola, "#,##0.000000000")
otrate = (rpd / 8) * 1.25
lblOTRate.Text = Format(otrate, "#,##0.000000000")
IsSSS = ConvertToBoolean(.Cells(4).Value)
IsPH = ConvertToBoolean(.Cells(5).Value) 'add
IsPAG = ConvertToBoolean(.Cells(6).Value) 'pos
IsMP = ConvertToBoolean(.Cells(11).Value)
IsFI = ConvertToBoolean(.Cells(10).Value)
CStatus = .Cells(9).Value
MPV = .Cells(12).Value
End With
ThisPayroll.Query = "Select * from tblpayroll where payrollperiod=? and empid=?"
ThisPayroll.AddParam("#payrollperiod", GetPeriod)
ThisPayroll.AddParam("#empid", id)
ThisPayroll.ExecQuery()
If ThisPayroll.RecordCount = Nothing Then
isUpdate = False
txtReg_Days.Text = 0
txtReg_OT.Text = 0
txtSP_Days.Text = 0
txtSP_OT.Text = 0
txtHoliday.Text = 0
txtHolidayOT.Text = 0
txtLate.Text = 0
txtAdjustment.Text = 0
txtSSSL.Text = 0
txtHDMFL.Text = 0
txtCA.Text = 0
txtDMA.Text = 0
txtRice.Text = 0
txtCloth.Text = 0
txtEmpMed.Text = 0
txtLaundry.Text = 0
txtMeal.Text = 0
Else
With ThisPayroll.DataSource
isUpdate = True
txtReg_Days.Text = .Rows(0)("regday")
txtReg_OT.Text = .Rows(0)("ot")
txtSP_Days.Text = .Rows(0)("spday")
txtSP_OT.Text = .Rows(0)("spdayot")
txtHoliday.Text = .Rows(0)("lholiday")
txtHolidayOT.Text = .Rows(0)("lhot")
txtLate.Text = .Rows(0)("hlate")
txtAdjustment.Text = .Rows(0)("salary_adj")
txtSSSL.Text = .Rows(0)("sss_loan")
txtHDMFL.Text = .Rows(0)("pag_loan")
txtCA.Text = .Rows(0)("cash_advance")
txtDMA.Text = .Rows(0)("depmed")
txtRice.Text = .Rows(0)("ricesub")
txtCloth.Text = .Rows(0)("clothing")
txtEmpMed.Text = .Rows(0)("empmed")
txtLaundry.Text = .Rows(0)("laundry")
txtMeal.Text = .Rows(0)("meal")
End With
End If
Compute()
End Sub
If you cannot make sure that something is selected elsewhere, you can last-minute check it like this:
Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView1.SelectionChanged
If dgEmp.SelectedRows.Count > 0 Then
LoadEmployeeInfo(dgEmp.SelectedRows.Item(0).Index)
End If
End Sub
It works only because you're using index zero, or else you would have to be careful for your index, too. Of course, this is assuming that dgEmp is not Nothing...
Also, notice that I attached this to the SelectionChanged event, as I don't think that the Click event will give you what you want, but I'll let that part for you to deal with. Have fun!

Error when saving a date column to the underlying database using sqlitedatadapter

I would appreciate any help in finding why I get an error when saving back to a database. The error is: "Concurrency violation: the UpdateCommand affected 0 of the expected 1 records."
I have worked out that the error only occurs when my table has a date field which I fill from the underlying database use a sqlitedatadapter as follows:
Public connstring As String = "Data Source=c:\VS-2019\SaveTable\SaveTable\Data\TestDb.db"
Public conn As New SQLiteConnection
Public Sub FillMainTables()
conn.ConnectionString = connstring
conn.Open()
DTAllCustomers.Rows.Clear()
sql = "SELECT * FROM Customers"
AllCustomersAdapter = New SQLiteDataAdapter(sql, conn)
AllCustomersAdapter.Fill(DTAllCustomers)
End Sub
I then modify a few records in the datatable(DTAllCustomers) using this code
For i = 0 To DTAllCustomers.Rows.Count - 1
If DTAllCustomers.Rows(i).Item("sitecode") = "RESI" Then
DTAllCustomers.Rows(i).Item("Email") = "Changed"
End If
Next
I then try to save the modified table back to the underlying database with:
Dim cbAllCustomers As New SQLiteCommandBuilder(AllCustomersAdapter)
AllCustomersAdapter.UpdateCommand = cbAllCustomers.GetUpdateCommand
Try
AllCustomersAdapter.Update(DTAllCustomers)
Catch ex As Exception
MsgBox(ex.Message)
End Try
When I remove the DATETIME columns in DTAllCustomers the error disappears and the update completes correctly. Does SQLite change the date structure/value of the DateTime columns between filling the datatable and saving back to the datatable?
UpdateCommand.CommandText is:
UPDATE [main].[sqlite_default_schema].[Customers] SET [Email] = #param1
WHERE (([PrimaryKey] = #param2)
AND ([CustomerNumber] = #param3)
AND ((#param4 = 1 AND [Zone] IS NULL) OR ([Zone] = #param5))
AND ((#param6 = 1 AND [SiteCode] IS NULL) OR ([SiteCode] = #param7))
AND ((#param8 = 1 AND [FirstName] IS NULL) OR ([FirstName] = #param9))
AND ((#param10 = 1 AND [Surname] IS NULL) OR ([Surname] = #param11))
AND ((#param12 = 1 AND [Villa] IS NULL) OR ([Villa] = #param13))
AND ((#param14 = 1 AND [Village] IS NULL) OR ([Village] = #param15))
AND ((#param16 = 1 AND [Address] IS NULL) OR ([Address] = #param17))
AND ((#param18 = 1 AND [Suburb] IS NULL) OR ([Suburb] = #param19))
AND ((#param20 = 1 AND [PostCode] IS NULL) OR ([PostCode] = #param21))
AND ((#param22 = 1 AND [Phone] IS NULL) OR ([Phone] = #param23))
AND ((#param24 = 1 AND [Mobile1] IS NULL) OR ([Mobile1] = #param25))
AND ((#param26 = 1 AND [Mobile2] IS NULL) OR ([Mobile2] = #param27))
AND ((#param28 = 1 AND [Email] IS NULL) OR ([Email] = #param29))
AND ((#param30 = 1 AND [System] IS NULL) OR ([System] = #param31))
AND ((#param32 = 1 AND [Panels] IS NULL) OR ([Panels] = #param33))
AND ((#param34 = 1 AND [Isolator] IS NULL) OR ([Isolator] = #param35))
AND ((#param36 = 1 AND [Inverter] IS NULL) OR ([Inverter] = #param37))
AND ((#param38 = 1 AND [SolarHotWater] IS NULL) OR ([SolarHotWater] = #param39))
AND ((#param40 = 1 AND [Skylight] IS NULL) OR ([Skylight] = #param41))
AND ((#param42 = 1 AND [Rebate] IS NULL) OR ([Rebate] = #param43))
AND ((#param44 = 1 AND [Quote] IS NULL) OR ([Quote] = #param45))
AND ((#param46 = 1 AND [Notes] IS NULL) OR ([Notes] = #param47))
AND ((#param48 = 1 AND [LastCleaned] IS NULL) OR ([LastCleaned] = #param49))
AND ((#param50 = 1 AND [BookedInDate] IS NULL) OR ([BookedInDate] = #param51))
AND ((#param52 = 1 AND [BookedInOrder] IS NULL) OR ([BookedInOrder] = #param53))
AND ((#param54 = 1 AND [Frequency] IS NULL) OR ([Frequency] = #param55))
AND ((#param56 = 1 AND [NextCallDue] IS NULL) OR ([NextCallDue] = #param57))
AND ((#param58 = 1 AND [Status] IS NULL) OR ([Status] = #param59))
AND ((#param60 = 1 AND [Source] IS NULL) OR ([Source] = #param61)))
The parameter values and the date columns are in this format - #5/30/2018 12:00:00 AM#, however in the command text there is a #paramX = 1 for each column in the table and the paramX being passed has a value of 0.

How to transform an SQL statement with Group by and Order By into a LINQ statement in vb.net

I have the following code working correctly, but was requested to combine it into one LINQ statement:
Dim AddlOrders = From ords In ctxi.V_TKT_HIST_BVs.AsEnumerable() _
Select ords Where (ords.CUST_NO = cstno) And (ords.ORIG_STA_ID <> "SWWEB") _
Order By ords.ORIG_TKT_NO Descending, ords.TKT_DT Descending
Dim AddlOrds As New Collection(Of V_TKT_HIST_BV)
Dim o As New V_TKT_HIST_BV
If (cstno Is Nothing) OrElse (AddlOrders Is Nothing) OrElse (AddlOrders.Count = 0) Then
AddlOrdersLabel.Text = "You have 0 additional orders."
AddlOrdersGrid.Visible = False
Else
For Each ord In AddlOrders
If prevord = String.Empty Then
prevord = ord.ORIG_TKT_NO
totord = ord.TOT
o = ord
ElseIf prevord = ord.ORIG_TKT_NO Then
totord += ord.TOT
Else
o.TOT = totord
AddlOrds.Add(o)
prevord = ord.ORIG_TKT_NO
totord = ord.TOT
o = ord
End If
Next
If o IsNot Nothing Then
AddlOrds.Add(o)
End If
Dim Addord = From ords In AddlOrds Order By ords.TKT_DT Descending
AddlOrdersGrid.DataSource = Addord
I have tried the following statement, but Visual Studio changes "Into os" to "Into os()" and gives a message that Definition of method os is not accessible in this context:
Dim orders = From o1 In ctxi.V_TKT_HIST_BVs
Where o1.CUST_NO = cstno
Group o1 By o1.TKT_DT, o1.ORIG_TKT_NO, o1.TOT
Into os() Select ORIG_ORD_NO, total = os.Sum(TOT),
tdate = os.Last(Function(v) v.TKT_DAT)
An example of the SQL would be like:
SELECT TOP (200) CUST_NO, EMAIL_ADRS_1, SUM(TOT) AS Expr1, ORIG_TKT_NO,
MIN(DISTINCT TKT_DT) AS Expr2
FROM V_TKT_HIST_BV
GROUP BY CUST_NO, EMAIL_ADRS_1, ORIG_TKT_NO
HAVING (EMAIL_ADRS_1 LIKE 'name%')
ORDER BY Expr2
Does anyone have an idea why it would change os into a method?
This would be it in C#:
AddlOrderGrid.DataSource=ctxi.V_TKT_HIST_BVs
.Where(t=>t.CUST_NO==cstno)
.Where(t=>t.ORIG_STA_ID!="SWWEB")
.GroupBy(t=>t.ORIG_TKT_NO)
.Select(t=> new {
CUST_NO=cstno,
EMAIL_ADRS_1=t.FirstOrDefault().EMAIL_ADRS_1,
TOT=t.SUM(u=>u.TOT),
ORIG_TKT_NO=t.Key,
TKT_DT=t.Min(u=>u.TKT_DT)
})
.OrderByDescending(t=>t.TKT_DT);
Converted to VB.NET:
Dim Addord = ctxi.V_TKT_HIST_BVs _
.Where(Function(t) t.CUST_NO = cstno) _
.Where(Function(t) t.ORIG_STA_ID <> "SWWEB") _
.GroupBy(Function(t) t.ORIG_TKT_NO) _
.Select(Function(t) New With { _
Key .CUST_NO = cstno, _
Key .EMAIL_ADRS_1 = t.FirstOrDefault().EMAIL_ADRS_1, _
Key .TOT = t.SUM(Function(u) u.TOT), _
Key .ORIG_TKT_NO = t.Key, _
Key .TKT_DT = t.Min(Function(u) u.TKT_DT) _
}).OrderByDescending(Function(t) t.TKT_DT)
If (Addord.Any()) Then
AddlOrderGrid.DataSource=Addord
Else
AddlOrdersLabel.Text = "You have 0 additional orders."
AddlOrdersGrid.Visible = False
Endif

VB IF statement to ask if NULL then apply default image instead

Inherited a VB website and am new to vb programming, so steep learning curve.
I have a site that searches and list all currently available cars in the UK for a leasing company.
the vehicle data is provided by an external comapany and links all the tech specs etc and images to a keyID. However...
If the vehicle has not been assigned an image it is not counted or displayed. I want to add an IF statement so that if the ImageId is Null then it will display a default 'awaiting image' jpg and would therefore still be listed to the public.
the page is http://www.carmyke.co.uk/search_prices.aspx with the 'Vans' dropping the most from the list.
I have included the code I think I need to update.
I think I need an IF statement for the .ImageId that if the SQL returns NULL then it uses a default image located in the same folder as defined by the appsettings
Hope this makes sense!?
<--- THE CODE --->
#Region "Methods"
Private Function GetVehicle(ByVal SearchBy As SearchBy, _
ByVal SearchText As String) As Data.LeasingPrices.Vehicle
Dim _Vehicle As New Data.LeasingPrices.Vehicle
Try
Dim _SQL As New Net.SQL
_SQL.AppendSQL("SELECT TOP 1 * ")
_SQL.AppendSQL("FROM vw_carmyke_Rates_Business ")
_SQL.AppendSQL("LEFT OUTER JOIN carmyke_SpecialOffers ON vw_carmyke_Rates_Business.CVehicleId = carmyke_SpecialOffers.CVehicleId ")
Select Case SearchBy
Case Hydrate.SearchBy.Make
_SQL.AppendSQL("WHERE Make = #SearchText ")
Case Hydrate.SearchBy.Model
_SQL.AppendSQL("WHERE MakeModel = #SearchText ")
Case Hydrate.SearchBy.Derivative
_SQL.AppendSQL("WHERE MakeModelDerivative = #SearchText ")
End Select
_SQL.AppendSQL("ORDER BY Rental_48_40;")
_SQL.AddParameter("#SearchText", SearchText, SqlDbType.VarChar)
_SQL.ConnectReader()
If _SQL.Validation.NoErrors Then
If _SQL.Reader.Read() Then
With _Vehicle
.CVehicleId = _SQL.Reader.SQLString("CVehicleId").ToInteger()
.Van = _SQL.Reader.SQLString("BodyStyle").Contains("Van")
.Make = _SQL.Reader.SQLString("Make")
.Model = _SQL.Reader.SQLString("Model")
.Derivative = _SQL.Reader.SQLString("Derivative")
.ImageId = _SQL.Reader.SQLString("ImageId") & ".jpg"
.Co2 = _SQL.Reader.SQLString("Co2").ToInteger()
.P11d = _SQL.Reader.SQLString("P11d").ToDouble()
.Business = _SQL.Reader.SQLString("Business").ToBoolean()
.Personal = _SQL.Reader.SQLString("Personal").ToBoolean()
.Details = _SQL.Reader.SQLString("Details")
.OfferPrice = _SQL.Reader.SQLString("OfferPrice").ToDouble()
If .OfferPrice = 0 Then _
.OfferPrice = _SQL.Reader.SQLString("Offer_48_40").ToDouble()
If .OfferPrice = 0 Then _
.OfferPrice = _SQL.Reader.SQLString("Rental_48_40").ToDouble()
.Commercial = _SQL.Reader.SQLString("Commercial").ToBoolean()
.Offer_24_20 = _SQL.Reader.SQLString("Offer_24_20").ToDouble()
.Offer_24_40 = _SQL.Reader.SQLString("Offer_24_40").ToDouble()
.Offer_24_60 = _SQL.Reader.SQLString("Offer_24_60").ToDouble()
.Offer_36_30 = _SQL.Reader.SQLString("Offer_36_30").ToDouble()
.Offer_36_60 = _SQL.Reader.SQLString("Offer_36_60").ToDouble()
.Offer_36_90 = _SQL.Reader.SQLString("Offer_36_90").ToDouble()
.Offer_48_40 = _SQL.Reader.SQLString("Offer_48_40").ToDouble()
.Offer_48_80 = _SQL.Reader.SQLString("Offer_48_80").ToDouble()
.Offer_48_120 = _SQL.Reader.SQLString("Offer_48_120").ToDouble()
If .Offer_24_20 = -1 Then
.Rental_24_20 = 0
ElseIf .Offer_24_20 > 0 Then
.Rental_24_20 = .Offer_24_20
Else
.Rental_24_20 = _SQL.Reader.SQLString("Rental_24_20").ToDouble()
End If
If .Offer_24_40 = -1 Then
.Rental_24_40 = 0
ElseIf .Offer_24_40 > 0 Then
.Rental_24_40 = .Offer_24_40
Else
.Rental_24_40 = _SQL.Reader.SQLString("Rental_24_40").ToDouble()
End If
If .Offer_24_60 = -1 Then
.Rental_24_60 = 0
ElseIf .Offer_24_60 > 0 Then
.Rental_24_60 = .Offer_24_60
Else
.Rental_24_60 = _SQL.Reader.SQLString("Rental_24_60").ToDouble()
End If
If .Offer_36_30 = -1 Then
.Rental_36_30 = 0
ElseIf .Offer_36_30 > 0 Then
.Rental_36_30 = .Offer_36_30
Else
.Rental_36_30 = _SQL.Reader.SQLString("Rental_36_30").ToDouble()
End If
If .Offer_36_60 = -1 Then
.Rental_36_60 = 0
ElseIf .Offer_36_60 > 0 Then
.Rental_36_60 = .Offer_36_60
Else
.Rental_36_60 = _SQL.Reader.SQLString("Rental_36_60").ToDouble()
End If
If .Offer_36_90 = -1 Then
.Rental_36_90 = 0
ElseIf .Offer_36_90 > 0 Then
.Rental_36_90 = .Offer_36_90
Else
.Rental_36_90 = _SQL.Reader.SQLString("Rental_36_90").ToDouble()
End If
If .Offer_48_40 = -1 Then
.Rental_48_40 = 0
ElseIf .Offer_48_40 > 0 Then
.Rental_48_40 = .Offer_48_40
Else
.Rental_48_40 = _SQL.Reader.SQLString("Rental_48_40").ToDouble()
End If
If .Offer_48_80 = -1 Then
.Rental_48_80 = 0
ElseIf .Offer_48_80 > 0 Then
.Rental_48_80 = .Offer_48_80
Else
.Rental_48_80 = _SQL.Reader.SQLString("Rental_48_80").ToDouble()
End If
If .Offer_48_120 = -1 Then
.Rental_48_120 = 0
ElseIf .Offer_48_120 > 0 Then
.Rental_48_120 = .Offer_48_120
Else
.Rental_48_120 = _SQL.Reader.SQLString("Rental_48_120").ToDouble()
End If
End With
Else
_Vehicle = Nothing
End If
Else
_Vehicle = Nothing
End If
_SQL.DisconnectReader()
Catch
_Vehicle = Nothing
End Try
Return _Vehicle
End Function
Public Function Vehicle(ByVal SearchText As String) As Data.LeasingPrices.Vehicle
Dim _Vehicle As New Data.LeasingPrices.Vehicle
_Vehicle = GetVehicle(Hydrate.SearchBy.Derivative, SearchText)
If _Vehicle Is Nothing Then
_Vehicle = GetVehicle(Hydrate.SearchBy.Model, SearchText)
End If
If _Vehicle Is Nothing Then
_Vehicle = GetVehicle(Hydrate.SearchBy.Make, SearchText)
End If
Return _Vehicle
End Function
Private Function GetSearchOption(ByVal SearchOption As String) As String
Dim _GetSearchOption As String = ""
Try
If Not HttpContext.Current.Session(SearchOption) Is Nothing Then _
_GetSearchOption = HttpContext.Current.Session(SearchOption)
Catch
_GetSearchOption = ""
End Try
Return _GetSearchOption
End Function
Public Function SearchOptions() As Data.LeasingPrices.SearchOptions
Dim _SearchOptions As New Data.LeasingPrices.SearchOptions
Try
With _SearchOptions
.FourByFour = GetSearchOption("FourByFour").ToBoolean()
.CityCar = GetSearchOption("CityCar").ToBoolean()
.Coupe = GetSearchOption("Coupe").ToBoolean()
.Estate = GetSearchOption("Estate").ToBoolean()
.Hatchback = GetSearchOption("Hatchback").ToBoolean()
.MPV = GetSearchOption("MPV").ToBoolean()
.Saloon = GetSearchOption("Saloon").ToBoolean()
.Sports = GetSearchOption("Sports").ToBoolean()
.Van = GetSearchOption("Van").ToBoolean()
.RentalFrom = GetSearchOption("RentalFrom").ToInteger()
.RentalTo = GetSearchOption("RentalTo").ToInteger()
If .RentalFrom = 0 And .RentalTo = 0 Then
.RentalFrom = Data.LeasingPrices.SearchOptions.DefaultRentalFrom
.RentalTo = Data.LeasingPrices.SearchOptions.DefaultRentalTo
End If
End With
Catch
_SearchOptions = Nothing
End Try
Return _SearchOptions
End Function
#End Region
#Region "Constructors"
Public Sub New()
End Sub
#End Region
End Class
End Namespace
I'm not familiar with the Net.SQL entity you're using, but it is usual to use something like the Convert.IsDBNull Method to check for a NULL database value.
An alternative is to use COALESCE in the query, like
SELECT TOP 1 [CVehicleId], ..more columns.., COALESCE([ImageId], 'AwaitingImage'), ..remaining columns..
You should really explicitly specify the columns, and put the column names in square brackets so that if you accidentally have a column name which happens to be an SQL keyword then it doesn't mistake it for a keyword.

Transactions in vb.net locks table and SELECT gets timeout

I have the following problem:
Inside one sqltransaction in vb.net I INSERT data into several tables.
it is something like this:
...
sqltransaction = connection.begintransaction
INSERT into table1
...
for i=1 to x
...
INSERT into table2
...
SELECT FROM table3
...
INSERT into table3
...
next i
sqltransaction.commit
...
Private Sub salveazaCerereaDeOferta()
If checkCompletion() = 1 Then
Dim conn As New SqlConnection(My.Settings.GestiuneService2012_beSQLConnectionString)
conn.Open()
Dim sqlTrans As SqlTransaction = conn.BeginTransaction()
Try
Dim cmdInsertCerereOferta As SqlCommand = conn.CreateCommand
cmdInsertCerereOferta.Transaction = sqlTrans
cmdInsertCerereOferta.CommandText = "INSERT INTO ListaCereriOferte (IDFurnizor,NrCerereOferta,DataCerereOferta,IDModTransCerereOferta,ObservatiiCerereOferta)" + _
" VALUES (#IDFurnizor,#NrCerereOferta,#DataCerereOferta,#IDModTransCerereOferta,#ObservatiiCerereOferta);" + _
" SELECT SCOPE_IDENTITY();"
cmdInsertCerereOferta.Parameters.Add("#IDFurnizor", SqlDbType.Int).Value = CInt(Me.t_IDFurnizor.Text)
cmdInsertCerereOferta.Parameters.Add("#NrCerereOferta", SqlDbType.Int).Value = CInt(Me.t_NumarCerereOferta.Text)
cmdInsertCerereOferta.Parameters.Add("#DataCerereOferta", SqlDbType.Date).Value = CDate(Me.t_DataCerereOferta.Text)
cmdInsertCerereOferta.Parameters.Add("#IDModTransCerereOferta", SqlDbType.Int).Value = 1
cmdInsertCerereOferta.Parameters.Add("#ObservatiiCerereOferta", SqlDbType.NVarChar).Value = Me.t_ObservatiiCerereOferta.Text
Dim IDCerereOferta As Integer = cmdInsertCerereOferta.ExecuteScalar
Dim ListaPieseCerereOferta = Me.CerereOfertaDataSet.ListaPieseCerereOferta.AsEnumerable
Dim ListaNecesarePePiesa = Me.CerereOfertaDataSet.NecesarePeOferta.AsEnumerable
Dim PieseOferta = From q In ListaPieseCerereOferta _
Select q
Dim cantTotalaPiese = Aggregate q In ListaPieseCerereOferta _
Into Sum(q.Cantitate)
Dim salvat As Integer = 0
Dim curIDPiesaDeSchimb As Integer
For Each piesa In PieseOferta
curIDPiesaDeSchimb = piesa.IDPiesaDeSchimb
Dim NecesarePePiesa = From p In ListaNecesarePePiesa _
Select p _
Order By p.IDNecesar Descending
Dim curIDNecesar As Integer
For Each necesar In NecesarePePiesa
curIDNecesar = necesar.IDNecesar
Dim cmdInsertPiesaCerereOferta As SqlCommand = conn.CreateCommand
cmdInsertPiesaCerereOferta.Transaction = sqlTrans
cmdInsertPiesaCerereOferta.CommandText = "INSERT INTO CereriOferte (IDCerereOferta,IDPiesaDeSchimb,Cantitate,UM,Observatii)" + _
" VALUES (#IDCerereOferta,#IDPiesaDeSchimb,#Cantitate,#UM,#Observatii);" + _
" SELECT SCOPE_IDENTITY();"
cmdInsertPiesaCerereOferta.Parameters.Add("#IDCerereOferta", SqlDbType.Int)
cmdInsertPiesaCerereOferta.Parameters.Add("#IDPiesaDeSchimb", SqlDbType.Int)
cmdInsertPiesaCerereOferta.Parameters.Add("#Cantitate", SqlDbType.Float)
cmdInsertPiesaCerereOferta.Parameters.Add("#UM", SqlDbType.NVarChar)
cmdInsertPiesaCerereOferta.Parameters.Add("#Observatii", SqlDbType.NVarChar)
Dim cmdInsertNecesarCerereOferta As SqlCommand = conn.CreateCommand
cmdInsertNecesarCerereOferta.Transaction = sqlTrans
cmdInsertNecesarCerereOferta.CommandText = "INSERT INTO NecesareCereriOferte (IDPiesaNecesar,IDPiesaCerereOferta)" + _
" VALUES (#IDPiesaNecesar,#IDPiesaCerereOferta)"
cmdInsertNecesarCerereOferta.Parameters.Add("#IDPiesaNecesar", SqlDbType.Int)
cmdInsertNecesarCerereOferta.Parameters.Add("#IDPiesaCerereOferta", SqlDbType.Int)
Select Case curIDNecesar
Case 0
cmdInsertPiesaCerereOferta.Parameters("#IDCerereOferta").Value = IDCerereOferta
cmdInsertPiesaCerereOferta.Parameters("#IDPiesaDeSchimb").Value = curIDPiesaDeSchimb
cmdInsertPiesaCerereOferta.Parameters("#Cantitate").Value = 1
cmdInsertPiesaCerereOferta.Parameters("#UM").Value = piesa.UM
cmdInsertPiesaCerereOferta.Parameters("#Observatii").Value = ""
For i = 1 To necesar.Cantitate
cmdInsertPiesaCerereOferta.ExecuteNonQuery()
salvat += 1
Me.tsspb_SalvareCerereOferta.Value = CInt(100 * salvat / cantTotalaPiese)
Next
Case Is > 0
Me.PieseNecesarePeOfertaTableAdapter.Fill(Me.CerereOfertaDataSet.PieseNecesarePeOferta, curIDNecesar, curIDPiesaDeSchimb, CInt(necesar.Cantitate))
Dim ListaPieseNecesarePeOferta = Me.CerereOfertaDataSet.PieseNecesarePeOferta.AsEnumerable
Dim PieseNecesareOferta = From q In ListaPieseNecesarePeOferta _
Select q
For i = 1 To necesar.Cantitate
cmdInsertPiesaCerereOferta.Parameters("#IDCerereOferta").Value = IDCerereOferta
cmdInsertPiesaCerereOferta.Parameters("#IDPiesaDeSchimb").Value = curIDPiesaDeSchimb
cmdInsertPiesaCerereOferta.Parameters("#Cantitate").Value = 1
cmdInsertPiesaCerereOferta.Parameters("#UM").Value = piesa.UM
cmdInsertPiesaCerereOferta.Parameters("#Observatii").Value = ""
Dim insertedIDPiesaCerereOferta As Integer = cmdInsertPiesaCerereOferta.ExecuteScalar
cmdInsertNecesarCerereOferta.Parameters("#IDPiesaNecesar").Value = PieseNecesareOferta(i - 1).IDPiesaNecesar
cmdInsertNecesarCerereOferta.Parameters("#IDPiesaCerereOferta").Value = insertedIDPiesaCerereOferta
cmdInsertNecesarCerereOferta.ExecuteNonQuery()
salvat += 1
Me.tsspb_SalvareCerereOferta.Value = CInt(100 * salvat / cantTotalaPiese)
Next
End Select
Next
Next
sqlTrans.Commit()
MsgBox("Cererea de oferta a fost salvata.")
Catch ex As Exception
Try
sqlTrans.Rollback()
MsgBox("A aparut o eroare." + vbNewLine + ex.ToString + vbNewLine + "RollBack success. Cererea nu a fost salvata.")
Catch ex2 As SqlException
If Not sqlTrans.Connection Is Nothing Then
MsgBox("An exception of type " & ex2.GetType().ToString() & _
" was encountered while attempting to roll back the transaction.")
End If
End Try
Finally
If conn.State = ConnectionState.Open Then conn.Close()
End Try
Else
MsgBox("Nu ai completat integral cererea de oferta!")
End If
End Sub
query that locks:
SELECT TOP (100) PERCENT dbo.qry_NecesareNerezolvate.IDPiesaNecesar, COUNT(dbo.NecesareCereriOferte.IDPiesaCerereOferta) AS CereriOferte,
dbo.qry_NecesareNerezolvate.IDNecesar, dbo.qry_NecesareNerezolvate.IDPiesaDeSchimb, dbo.qry_NecesareNerezolvate.Cantitate
FROM dbo.qry_NecesareNerezolvate LEFT OUTER JOIN
dbo.NecesareCereriOferte ON dbo.qry_NecesareNerezolvate.IDPiesaNecesar = dbo.NecesareCereriOferte.IDPiesaNecesar
GROUP BY dbo.qry_NecesareNerezolvate.IDPiesaNecesar, dbo.qry_NecesareNerezolvate.IDNecesar, dbo.qry_NecesareNerezolvate.IDPiesaDeSchimb,
dbo.qry_NecesareNerezolvate.Cantitate
qry_NecesareNerezolvate:
SELECT TOP (100) PERCENT dbo.Necesare.IDPiesaNecesar, dbo.Necesare.IDNecesar, dbo.Necesare.IDPiesaDeSchimb, dbo.Necesare.Cantitate, dbo.Necesare.UM,
dbo.Necesare.Observatii
FROM dbo.Necesare LEFT OUTER JOIN
dbo.qry_NecesareComandateRezolvate ON dbo.Necesare.IDPiesaNecesar = dbo.qry_NecesareComandateRezolvate.IDPiesaNecesar
WHERE (dbo.qry_NecesareComandateRezolvate.IDPiesaNecesar IS NULL)
qry_NecesareComandateRezolvate:
SELECT dbo.Necesare.IDPiesaNecesar, dbo.NecesareComenzi.IDPiesaComanda, dbo.NecesareRezolvate.IDBonTransfer
FROM dbo.Necesare LEFT OUTER JOIN
dbo.NecesareComenzi ON dbo.Necesare.IDPiesaNecesar = dbo.NecesareComenzi.IDPiesaNecesar LEFT OUTER JOIN
dbo.NecesareRezolvate ON dbo.Necesare.IDPiesaNecesar = dbo.NecesareRezolvate.IDPiesaNecesar
WHERE (dbo.NecesareComenzi.IDPiesaComanda IS NOT NULL) OR
(dbo.NecesareRezolvate.IDBonTransfer IS NOT NULL)
for i=1: insert, select then insert is working
then i=2 and: INSERT into table2... is working but SELECT FROM table1 and table3... gets timeout...
I don't understand why!
PS: If I break the code before second run of SELECT FROM table3 then go to SSMS and run the select query it gets timeout too...
In your code sample below, you have the transaction open till the end of the For Loop.
It seems to me that when i =1 , the transaction gets opened and a insertion is made. Now when i=2 , the to be inserted row when i=1 is in uncomitted state and if your select is joining to the table1 the lock level would have escalated to table level and locked everything down. Move the commit to inside the for loop and check how it goes.
for i=1 to x
...
INSERT into table2
...
SELECT FROM table3
...
INSERT into table3
...
next i
sqltransaction.commit