Declan Basile
asked on
How to change the parameter value and re-use a sqlCommand object
What's the appropriate way to re-use a sqlCommand and re-execute a datareader in which all I want to change is a parameter value? See code below. Note: Executing the Reader in the first iteration works fine, then it bombs on the second iteration of the loop.
cn2 = New SqlConnection(GlobalVariab les.strCon n)
cn2.Open()
cmd2 = New SqlCommand(m_strNameLookup SQL, cn2)
cmd2.Parameters.Add("@Item Id", SqlDbType.Int)
Do While <some condition>
cmd2.Parameters("@ItemId") .Value = <some value that's different with each iteration of the loop>
rdr2 = cmd2.ExecuteReader
rdr2.Read()
Loop
cn2 = New SqlConnection(GlobalVariab
cn2.Open()
cmd2 = New SqlCommand(m_strNameLookup
cmd2.Parameters.Add("@Item
Do While <some condition>
cmd2.Parameters("@ItemId")
rdr2 = cmd2.ExecuteReader
rdr2.Read()
Loop
ASKER
It still bombs on the .executereader line during the second iteration of the loop ...
Do While rdr1.Read
lngRootNodeId = rdr1("Id")
cmd2.Parameters.Clear()
cmd2.Parameters.Add("@Item Id", SqlDbType.Int).Value = lngRootNodeId
rdr2 = cmd2.ExecuteReader
rdr2.Read()
Loop
Do While rdr1.Read
lngRootNodeId = rdr1("Id")
cmd2.Parameters.Clear()
cmd2.Parameters.Add("@Item
rdr2 = cmd2.ExecuteReader
rdr2.Read()
Loop
What error you are getting?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you!. I was missing the rdr2.Close. I was able to just change the value of the parameter instead of clearing and re-adding the parameter every time. The following code worked ...
cmd2 = New SqlCommand(m_strNameLookup SQL, cn2)
cmd2.Parameters.Add("@Item Id", SqlDbType.Int)
Do While rdr1.Read
lngRootNodeId = rdr1("Id")
cmd2.Parameters("@ItemId") .Value = lngRootNodeId
rdr2 = cmd2.ExecuteReader
rdr2.Read()
strRootNodeName = rdr2("ItemName")
rdr2.Close()
cmd2 = New SqlCommand(m_strNameLookup
cmd2.Parameters.Add("@Item
Do While rdr1.Read
lngRootNodeId = rdr1("Id")
cmd2.Parameters("@ItemId")
rdr2 = cmd2.ExecuteReader
rdr2.Read()
strRootNodeName = rdr2("ItemName")
rdr2.Close()
Glad to help, Yes you have to close the reader
cmd2.Parameters("@ItemId")
rdr2 = cmd2.ExecuteReader
rdr2.Read()
cmd2.Parameters.Clear()
cmd2.Parameters.Add("@Item
Loop