Click here to Skip to main content
15,886,056 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please help me write a query to update database fields where the values are in an array:
this is my code but it gives error (arr1 not a built in function)

VB
'get array items from listbox
        Dim arr1()
        ReDim arr1(ListBox1.Items.Count - 1)
        ListBox1.Items.CopyTo(arr1, 0)


        Dim query3 As String = "UPDATE   tblcand   SET votes = votes +1  where id = ( arr1() )"
        Using cmd1 As New SqlCommand(query3, con)
            con.Open()
            cmd1.ExecuteNonQuery()
            con.Close()
        End Using



I Would also appreciate if its used in a stored procedure
Thanks
Posted
Comments
coded007 25-Aug-14 9:10am    
are you using one value or set of values to update?
Member 10316149 25-Aug-14 18:07pm    
Set of values like (1,6,9,10)

1 solution

Change your = to an in clause.
Then use string.join() to format the values for the query.
VB
Dim arr1 As Array
ReDim arr1(ListBox1.Items.Count - 1)
ListBox1.Items.CopyTo(CType(arr1, Object()), 0)

Dim query3 As String = "UPDATE   tblcand   SET votes = votes +1  where id IN (SELECT * FROM SplitIntCsv(@IdsInArray))"
Using cmd1 As New SqlCommand(query3, con)
    cmd1.Parameters.AddWithValue("@IdsInArray", String.Join(",", arr1))
    con.Open()
    cmd1.ExecuteNonQuery()
    con.Close()
End Using


Add this function to split your CSV into a table.
SQL
CREATE FUNCTION dbo.SplitIntCsv
(
    @String NVARCHAR(4000)
)
RETURNS TABLE 
AS
RETURN 
(
    WITH Split(stpos,endpos) 
    AS(
        SELECT 0 AS stpos, CHARINDEX(',',@String) AS endpos
        UNION ALL
        SELECT endpos+1, CHARINDEX(',',@String,endpos+1)
            FROM Split
            WHERE endpos > 0
    )
    SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1))
    FROM Split
)
 
Share this answer
 
v2
Comments
Member 10316149 25-Aug-14 17:57pm    
Thanks Jared
But it gives this error ("Conversion failed when converting the nvarcar value to data type int")
the error occurs at cmd1.ExecuteNonQuery()
SteveyJDay 27-Aug-14 10:02am    
I added an SQL function that will fix your problem.
Member 10316149 27-Aug-14 16:22pm    
@Jared There is a syntax error at:
ReDim arr1(ListBox1.Items.Count - 1)
the error message is: (Redim statement requires an array)
thank you.
SteveyJDay 27-Aug-14 16:49pm    
Change Dim arr1 As Array to Dim arr1

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900