any possible way to populate datagridview with large data faster? - vb.net

here's my code. it's already working. but populating datagridview is taking too long to fill.
Public Sub Reprint_Pop1(ByVal i As Integer, ByVal grd As DataGridView, ByVal display As Integer, Optional ByVal search As String = Nothing, Optional ByVal a As String = Nothing, Optional ByVal b As String = Nothing)
Try
cn.Open()
Select Case i
Case 0
sql = "select pos.posno, transdate, transtime, sum(trans.qty) as totalitems, format(sum(trans.amount),2) as amount, printdesc from tblpostrans as trans
left join tblpos as pos on trans.posno = pos.posno
where pos.status = 'Completed' group by pos.posno order by transid desc limit 0, #display"
Case 1
sql = "select pos.posno, transdate, transtime, sum(trans.qty) as totalitems, format(sum(trans.amount),2) as amount, printdesc from tblpostrans as trans
left join tblpos as pos on trans.posno = pos.posno
where pos.status = 'Completed' and (transtime like #search or transdate like #search or trans.amount like #search or pos.posno like #search or printdesc like #search) group by pos.posno order by transid desc limit 0, #display"
Case 2
sql = "select pos.posno, transdate, transtime, sum(trans.qty) as totalitems, format(sum(trans.amount),2) as amount, printdesc from tblpostrans as trans
left join tblpos as pos on trans.posno = pos.posno
where pos.status = 'Completed' and str_to_date(transdate, '%Y-%m-%d') between #a and #b and (transtime like #search or transdate like #search or trans.amount like #search or pos.posno like #search or printdesc like #search) group by pos.posno order by transid desc limit 0, #display"
End Select
cmd = New MySqlCommand(sql, cn)
cmd.Parameters.AddWithValue("display", display)
cmd.Parameters.AddWithValue("search", "%" & search & "%")
cmd.Parameters.AddWithValue("a", a)
cmd.Parameters.AddWithValue("b", b)
dr = cmd.ExecuteReader
grd.Rows.Clear()
If dr.HasRows = True Then
Dim col(4)
While dr.Read
col(0) = dr("posno")
col(1) = dr("transdate")
col(2) = dr("transtime")
col(3) = dr("amount")
col(4) = dr("totalitems")
grd.Rows.Add(col)
End While
End If
Catch ex As Exception
MsgErr(ex.Message, "Error Encounter")
Finally
cn.Close()
End Try
End Sub
is there any way possible to optimize this ? like using adapter or binding datasource? if that's the way. how can i include it in the module ?

Related

Display number of rows and columns

I have in my table MS Access named ( Table1 ) two fields ( ID1 - Team1 ).
With NumericUpDown1 i select the number of rows that i want to display after randomize in DataGridView2.With NumericUpDown2 i select the number of columns that i want to display after randomize in DataGridView2.If i choose with NumericUpDown2 only one column ( the number 1 ) it work very well with this query :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Con_randomize()
Dim rows As Integer
If Not Integer.TryParse(NumericUpDown1.Value, rows) Then
MsgBox("NUMBER NOT AVAILABLE", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Error")
NumericUpDown1.Value = ""
NumericUpDown1.Focus()
Exit Sub
End If
If NumericUpDown2.Value = 1 Then
Dim sql As String = String.Format("SELECT Top {0} ID1,Team1 From Table1 ORDER BY RND(-(100000*ID1)*Time())", rows)
InfoCommand = New OleDbCommand(sql, Con_randomize)
InfoAdapter = New OleDbDataAdapter()
InfoAdapter.SelectCommand = InfoCommand
InfoTable = New DataTable()
InfoAdapter.Fill(InfoTable)
DataGridView2.DataSource = InfoTable
DataGridView2.Columns(0).HeaderText = "NUMERO"
DataGridView2.Columns(1).HeaderText = "CATEGORY1"
End If
End Sub
How to make if i choose with NumericUpDown2 the number 2 or 3 columns i want to display in Datagridview2.
The columns will be named ( CATEGORY2 - CATEGORY3 ) . for example ( 1 Victor - David - Vincent ) ( 2 wiliam- George - Joseph ) ..in my only field named Team1 I have a hundred of the names
I'm not 100% sure why you need a query to initialize the data, but give this a go. It will automatically create the columns the way you need them.
' If NumericUpDown2.Value = 1 Then ' Comment This If Block Out
' Create the Teams String
Dim teamsString as New System.Text.StringBuilder("")
For i as Integer = 1 to Convert.ToInt32(NumericUpDown2.Value)
teamsString.Append(", (SELECT Top 1 Team1 From Table1 ORDER BY RND(-(100000*ID1)*Time())) as Category" + i.ToString())
Next
Dim sql As String = String.Format("SELECT Top {0} ID1" + teamsString.ToString() + " From Table1 ORDER BY RND(-(100000*ID1)*Time())", rows)
InfoCommand = New OleDbCommand(sql, Con_randomize)
InfoAdapter = New OleDbDataAdapter()
InfoAdapter.SelectCommand = InfoCommand
InfoTable = New DataTable()
InfoAdapter.Fill(InfoTable)
DataGridView2.DataSource = InfoTable
DataGridView2.Columns(0).HeaderText = "NUMERO"
' Don't Need This, We Made It the Binding Name
' DataGridView2.Columns(1).HeaderText = "CATEGORY1"

how to use an in clause to check if a column is a certain string or not when referencing 3 tables

I have this SQL statement and it joining 2 tables...
SELECT TRIDENT.Maintenance.RCFAs.*, TRIDENT.Maintenance.Equipment.EquipmentName
FROM TRIDENT.Maintenance.RCFAs
LEFT JOIN TRIDENT.Maintenance.Equipment
ON TRIDENT.Maintenance.Equipment.EquipmentId = TRIDENT.Maintenance.RCFAs.EquipmentId
WHERE 1 = 1
Now I have to reference a third table because I have a dropdown by the name of components that we will use to lookup stuff on the table named TRIDENT.Maintenance.RCFAXrefComponents. So if "bolts" is selected from the dropdown it will look up the YEAR and RCFAID which makes a unqiue key for both RCFAXrefComponents and RCFAs and checks if there are any rows in RCFAs that had "bolts" in the component column when looking up that YEAR and RCFAId. A coworker suggested I use an IN clause to check if the YEAR and RCFAId is in that RCFAXrefComponents. He said it might be tricky, but I'm a little lost on how to do this.
Below is the RCFAs table that I want to grab the YEAR and RCFAId values together and lookup on the other to see if that bolt is also there. Then it should bring up the line item on RCFAs table to output to user
this is RCFAXrefComponents table below
Public Shared Function GetRCFAList(rcfaNumber As Integer?, description As String,
failureType As String, equipmentDescription As String, componentSelection As String) As List(Of RCFA)
Dim sql = "SELECT r.*, e.EquipmentName FROM TRIDENT.Maintenance.RCFAs AS r LEFT JOIN TRIDENT.Maintenance.Equipment AS e ON e.EquipmentId = r.EquipmentId JOIN TRIDENT. Maintenance.RCFAXrefComponents AS c ON c.Year = r.Year AND c.RCFAId = r.RCFAId WHERE"
If failureType <> "" Then
sql += " AND RCFAs.FailureType = '" & failureType.ToUpper & "'"
End If
If description <> "" Then
sql += " AND RCFAs.ShortDesc LIKE '%" & description.ToUpper & "%'"
End If
If equipmentDescription <> "" Then
sql += " AND Equipment.EquipmentName LIKE '%" & equipmentDescription.ToUpper & "%'"
End If
If componentSelection <> "" Then
sql += " c.ComponentId = '%" & componentSelection.ToUpper & "%'"
End If
Dim dbConn As New Trident.Core.DBConnection
Dim ds = dbConn.FillDataSet(sql)
Dim tmpList As New List(Of RCFA)
For Each dr As DataRow In ds.Tables(0).Rows
tmpList.Add(New RCFA(New Trident.Objects.Maintenance.RCFA.RCFA(dr)))
Next
Return tmpList
End Function
Just use a simple JOIN with the RFCAXrefComponents table, and a WHERE clause that filters the component ID.
SELECT r.*, e.EquipmentName
FROM TRIDENT.Maintenance.RCFAs AS r
LEFT JOIN TRIDENT.Maintenance.Equipment AS e
ON e.EquipmentId = r.EquipmentId
JOIN TRIDENT.Maintenance.RCFAXrefComponents AS c
ON c.Year = r.Year
AND c.RCFAId = r.RCFAId
WHERE c.ComponentID = 'BOLTS'
I may be confused but it sounds like you need to use EXISTS.
SELECT r.*,
e.EquipmentName
FROM TRIDENT.Maintenance.RCFAs r
LEFT JOIN TRIDENT.Maintenance.Equipment e ON e.EquipmentId = r.EquipmentId
WHERE EXISTS ( SELECT 1
FROM TRIDENT.Maintenance.RCFAXrefComponents c
WHERE c.Year = r.Year
AND c.RCFAId = r.RCFAId
AND c.ComponentId LIKE '%BOLTS%' )
you may not need the c.ComponentId LIKE '%BOLTS%' you might just want c.ComponentId = 'BOLTS'

How to determine if sql INSERTED or UPDATED?

Say I have a function like this:
Private Function addNicheMerge(ByVal tyNicheMergePOLE As typeNicheMergePOLE) As Integer Implements IGenie.addNicheMerge
Dim objParameterValues As New clsParameterValues
Dim objCon As DbConnection
Dim paramValues() As DbParameter
Dim iConnectionBLL As DataAccessLayer.Connection.iConnectionBLL
iConnectionBLL = New clsConnectionBLL()
Dim intCount As Integer
Try
tyAcornCollision = New typeAcornCollision
objParameterValues = New clsParameterValues
objCon = iConnectionBLL.getDatabaseTypeByDescription("GENIE2")
Using objCon
Dim strSQL As String
strSQL = "If NOT Exists (SELECT * FROM dbNicheMergeLog WHERE MasterID=#MasterID AND ChildID = #ChildID) "
strSQL = strSQL & "INSERT INTO dbNicheMergeLog (MasterID, ChildID, DateAdded, GenieUpdated, done, CheckedByUser, MergeTypeID, Usercode, LastUpdated) VALUES (#MasterID, #ChildID, getDate(), 0, 0, #CheckedByUser, #MergeTypeID, '', " & _ "GetDate()) Else Update dbNicheMergeLog SET LastUpdated = getdate() WHERE MasterID=#MasterID AND ChildID = #ChildID"
objParameterValues.AssignParameterValues("#MasterID", tyNicheMergePOLE.MasterID, 1)
objParameterValues.AssignParameterValues("#ChildID", tyNicheMergePOLE.ChildID, 1)
objParameterValues.AssignParameterValues("#MergeTypeID", tyNicheMergePOLE.MergeTypeID, 1)
objParameterValues.AssignParameterValues("#CheckedByUser", 0, 1)
paramValues = objParameterValues.getParameterValues
intCount = clsDatabaseHelper.ExecuteNonQuery(objCon, CommandType.Text, strSQL, paramValues)
Return intCount
End Using
Catch ex As Exception
Return -2
Finally
' If objCon.State = ConnectionState.Open Then
' objCon.Close()
' End If
objCon = Nothing
End Try
End Function
Is there a way to determine whether an insertion or update took place?
if you are using sql server, you could use an output clause to determine if an update happened
Update dbNicheMergeLog SET LastUpdated =
getdate() WHERE MasterID=#MasterID AND
ChildID = #ChildID
OUTPUT count(*)
Then in vb use
dim updateCount as int = Convert.ToInt32(clsDatabaseHelper.ExecuteScalar())
Try this SQL:
WITH new (
MasterID
,ChildID
,DateAdded
,GenieUpdated
,done
,CheckedByUser
,MergeTypeID
,Usercode
,LastUpdated
)
AS(
SELECT
#MasterID
,#ChildID
,getDate()
,0
,0
,#CheckedByUser
,#MergeTypeID
,''
,getdate()
)
MERGE INTO dbNicheMergeLog t
USING new
ON t.MasterID = new.MasterID
AND t.ChildID = new.ChildID
WHEN NOT MATCHED BY TARGET THEN
INSERT (
MasterID
,ChildID
,DateAdded
,GenieUpdated
,done
,CheckedByUser
,MergeTypeID
,Usercode
,LastUpdated
)
VALUES (
new.MasterID
,new.ChildID
,new.DateAdded
,new.GenieUpdated
,new.done
,new.CheckedByUser
,new.MergeTypeID
,new.Usercode
,new.LastUpdated
)
OUTPUT $action as Action
;
You can use
Output deleted.*
in your update query to get the results that were lost on update, something like this:
Create Table #abctest(
Id int identity,Name varchar(200))
Insert into #abctest(Name)
Values('abcd'),('bcde'),('cdef'),('defg'),('efgh'),('fghi')
Update #abctest Set Name='xyz' OUTPUT Deleted.* Where Id=2
The above query will give you an output
Id Name
2 bcde

datagrid view change color depend of status in winform application

I have a function like this:
Sub KPIColorchange()
'take 80 percenatge
Dim perc80 As Integer = 80
value80 = DefaultKPI * perc80 / 100
Dim carid As String
Dim strr As String = "select t.TBarcode as carid from Khanger_tbl k
inner join transaction_tbl t on k.transactid=t.transactID"
strr = strr + " where tid= " & tid & " and requested=1 and delivered=0 and status=3
and DATEDIFF(n, CAST(paydate AS DATETIME), GETDATE()) >=" & value80 & ""
Dim cmdr As New SqlCommand(strr, con.connect)
dr2 = cmdr.ExecuteReader
While dr2.Read
If dr2("carid") Is DBNull.Value Then
carid = ""
Else
carid = dr2("carid")
End If
Dim cnt As Integer = DGVall.Rows.Count
For i = 0 To cnt - 2
If DGVall.Rows(i).Cells(0).Value.ToString().Equals(carid) Then
DGVall.Rows(i).DefaultCellStyle.BackColor = Color.Fuchsia
End If
Next
End While
dr2.Close()
con.disconnect()
'take 100 percentage
Dim perc100 As Integer = 100
value100 = DefaultKPI * perc100 / 100
Dim str100 As String = "select t.TBarcode as carid from Khanger_tbl k
inner join transaction_tbl t on k.transactid=t.transactID"
str100 = str100 + " where tid= " & tid & " and requested=1 and delivered=0 and status=3 and
DATEDIFF(n, CAST(paydate AS DATETIME), GETDATE()) >=" & value100 & ""
Dim cmd100 As New SqlCommand(str100, con.connect)
dr2 = cmd100.ExecuteReader
While dr2.Read
If dr2("carid") Is DBNull.Value Then
carid = ""
Else
carid = dr2("carid")
End If
Dim cnt As Integer = DGVall.Rows.Count
For i = 0 To cnt - 2
If DGVall.Rows(i).Cells(0).Value.ToString().Equals(carid) Then
DGVall.Rows(i).DefaultCellStyle.BackColor = Color.OrangeRed
End If
Next
End While
dr2.Close()
con.disconnect()
End Sub
I have a grid view ,in that grid view i am loading some Requested carid we already set some time interval to Location.depend on the location time interval i have to change color in grid view
if the car requested time coming 80 percentage of location interval time then i will change to one color .
if the car requested time coming 100 percentage of location interval time then i will change to OrangeRed only this much things i am doing here..normally my datagrid view contains morethan 100 above records. this function i am calling in Timer_tick event in each one minute.
but becouse of this function my system get slow or some time system get hang.how i can optimize this code?
any help is very appreciable in advance

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