First time poster - medium length reader. I'm an entry level programmer, currently working on passing a SQL Stored Procedure some information that might contain a single quote (').
In the past, we've attempted to just use a .Replace("'","''") when passing this information, but recently, we've run into some issues with returning data and having the set changes and replaces in about 20 places (corporate, woo!).
I've been looking at using SQL Parameters to not have to worry about these buggers: ', but cannot see/understand the difference in my below code. The first block was the original working version. The second is my attempt at introducing @paras.
SQL is being passed through ByVal as a String
Previous Code:
Dim dbConnection As New SqlConnection(ConnectionString)
Dim dbCommand As New SqlCommand(SQL, dbConnection)
MsgBox(dbCommand.CommandText.ToString) //Returns proper procedure/paras
dbCommand.CommandTimeout = CommandTimeout
dbConnection.Open()
dbCommand.ExecuteNonQuery()
Code with SQL Parameters:
Dim dbConnection As New SqlConnection(ConnectionString)
Dim dbCommand As New SqlCommand("@SQL", dbConnection)
dbCommand.Parameters.Add("@SQL", SqlDbType.VarChar).Value = SQL
MsgBox(dbCommand.CommandText.ToString) //Returns "@SQL"
dbCommand.CommandTimeout = CommandTimeout
dbConnection.Open()
dbCommand.ExecuteNonQuery()
I feel the second block should be returning the same information. A MsgBox from the first block will return the proper SQL. The second however, just returns "@SQL", not the SQL value it seems to assign.
Is there a special way of refreshing the SQL Command? Am I unable to only declare @SQL and replace it later?
Took a peek around MSDN as well as quite a few searches, leading me here already, with no luck.