VB.NET Sql Parameters: I need help!

I decided to clean up my code moving some Sub from my Forms in a new class, but when i did it Sql parameters start doing weird things! someone can tell me what happened? thanks!

Public Sub Delete(ByVal Table As String)
        //Opening connection
        //Clearing transactions chronology
        Dim Sql As String = "Delete from @Table"
        myCmd = New SqlCommand(Sql, myConn)
        myCmd.Parameters.Add("@Table", SqlDbType.VarChar).Value = Table
        MsgBox("Cronologia ordini canellata.")
End Sub
Private Sub Del_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Del.Click
        Dim Tool As New SQLTools()
    End Sub

Open in new window

Visual Studio throw an SqlException "Declare variable @Table" on line
Dim Sql As String = "Delete from @Table"

Open in new window

Sub Delete

Open in new window

Sub Del_Click

Open in new window

are sub of two different classes. https://pastebin.com/L1gxvS4X
Simone GarofaloAsked:
Who is Participating?
Kyle AbrahamsConnect With a Mentor Senior .Net DeveloperCommented:
but that's not what your code is doing.

your code is essentially doing:

declare @table varchar(100)
set @table = 'nameoftable'
delete from @table

you either have to convert that to dynamic sql or just pass in the correct query.

Normally parameters are used for a where clause.


delete from table where id = @id

then you would pass in @id.  The query doesn't change, just the parameter value.
Kyle AbrahamsSenior .Net DeveloperCommented:
I don't believe you can delete from a table that way.

I would do a replace instead.

Dim Sql As String = Replace("Delete from @Table", "@Table", Table)

Open in new window

Simone GarofaloAuthor Commented:
I will try it! but if a try this query "DELETE FROM [table_name]" on my db, ti works fine
Kyle AbrahamsSenior .Net DeveloperCommented:
Auto Close.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.