Can anyone please help me on the following:
I have created a SQL Server stored procedure as follows:
create procedure prcGet_sub_menu_list
#sub_menu char(5)
as
begin
select
'menu_code' = menu_code
'menu_name' = menu_name
from sub_menu_master
where menu_code = #sub_menu
end
return
Now i am calling this procedure from VB.NET, but i get an error like 'Stored procedure prcGet_sub_menu_list expects parameter #sub_menu which was not supplied'. Please help me on the same. The code which i have in VB.NET is as follows:
Imports System.Data
Imports System.Data.SqlClient
Dim sqlConn as New SqlClient.SqlConnection
sqlConn.ConnectionString = "........"
sqlConn.Open()
Dim menuCode as string
menuCode = cboDetails.selectedItem
Dim sqlCmd as New SqlCommand
sqlCmd.Connection = Connection.sqlConn
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.CommandText = "prcGet_sub_menu_list"
sqlCmd.Parameter.Add("menuCode", SqlDbType.Char)
Dim sqlDA as New SqlDataAdapter()
sqlDA.SelectCommand = sqlCmd
Dim sqlDT as New DataTable
sqlDA.Fill(sqlDT)
This is the code that i have written and it gives me the error:
'Stored procedure prcGet_sub_menu_list expects parameter #sub_menu which was not supplied'.
Please give me some help on the same.
Regards,
George
You have to give the same parameter name and type like in your stored procedure.
sqlCmd.Parameters.Add(New SqlParameter("#sub_menu", SqlDbType.Char, 5)).Value = "Joe"
Geetha.
As the message implies, you should add a parameter named "sub_menu" in the same way as you're adding the "menuCode" parameter. You should probably also give it a value:
sqlCmd.Parameter.Add("sub_menu", SqlDbType.Char).Value = "Blah"
(Of course, I don't know what the correct type is, so Char is just an example.)
You need to use the correct parameter name
Something like
sqlCmd.Parameter.Add("#sub_menu", SqlDbType.Char)
And assign it a value
Something like
sqlCmd.Parameters("#sub_menu").Value = val
Have a look at SqlCommand.Parameters Property
and maybe Lesson 07: Using Stored Procedures
A couple things. Parameter should be Parameters. Also sqlCmd.Parameters.Add is deprecated so use sqlCmd.Parameters.AddWithValue:
sqlCmd.Parameters.AddWithValue("menuCode", menuCode)
Related
As the title says I have a MS Access database from where I need to find a specific dataset determined by a String Value. the reason for having to do this is so I can find the value of a single cell in this datase which has to be used as a path to find a certain file. my approach so far is the following:
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ExaptLokal.accdb")
Dim cmd As New OleDb.OleDbCommand
Dim dt As New DataTable
Dim da As New OleDb.OleDbDataAdapter
Dim sql As String
sql = "SELECT NC_KEY FROM EXAPT_NC_KOPF_DATEN WHERE NC_PROGRAMM_NAME =" & ProgrammNr.Text.ToString
MsgBox(sql)
conn.Open()
cmd.Connection = conn
cmd.CommandText = sql
da.SelectCommand = cmd
da.Fill(dt)
fullpath = dt.ToString
at the end I would like to have the result from my SQL Query as the value of my "fullpath" variable but so far the da.Fill(dt) row is giving me a hard time saying there is a conflict with the datatype.
Is the datatable even needed in this case or might I be able to skip that step and get the result of the query directly in the fullpath variable?
Thanks to everyone in advance
Edit: Thanks for the help (though not the friendliest but who am I to judge) I finally got it to work with the Execute Scalar method. I would just wish newbies to this website would be greeted a little better lol
have a great day
I moved the connection string to a class level variable so you can use it in other methods.
I separated your data access code from your user interface code passing the value from the text box to a function that returns the path.
I changed your select statement to use parameters. Always use parameters to avoid sql injection and avoid errors.
Use Using...End Using blocks to ensure that your database objects are closed and disposed. This Using block covers both the command and the connection.
You can pass the .CommandText and the .Connection directly to the constructor of the command.
When adding parameters to the parameters collection you provide the parameter name, the datatype form the database, and the size of the field. I had to guess at the type and size so, check your database for the actual values.
Since you are expecting a single value you can use .ExecuteScalar.
Private ConStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ExaptLokal.accdb"
Private Function GetPath(ProgrammNr As String) As String
Dim fullpath As String
Dim sql = "SELECT NC_KEY FROM EXAPT_NC_KOPF_DATEN WHERE NC_PROGRAMM_NAME = #ProgrmmNr"
Using conn As New OleDb.OleDbConnection(ConStr),
cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.Add("#ProgrmmmNr", OleDbType.VarChar, 100).Value = ProgrammNr
conn.Open()
fullpath = cmd.ExecuteScalar.ToString
End Using
Return fullpath
End Function
Usage...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fullpath = GetPath(ProgrammNr.Text)
End Sub
I'm trying to create a sub to add as many parameters as I want, I used to do this in vb6 but here in vb.net it requires me to provide the parameter name (.add(#parameter, value)). I need to find a way to do it without knowing the parameter name, i used to send the parameters using the parameter order in the stored procedure, here the code:
Public Sub EjecutarSP(ByVal SP As String, ByVal ParamArray Parametros() As Object)
Dim cnn As New SqlConnection(ConfigurationSettings.AppSettings("connString").ToString)
Dim cmd As New SqlCommand(SP, cnn)
Dim i As Integer
Dim Param As SqlParameter
Try
For i = 0 To UBound(Parametros)
Param = New SqlParameter("str", Parametros(i))
cmd.Parameters.Add(Param)
Next
cmd.CommandTimeout = 0
cmd.CommandType = CommandType.StoredProcedure
If cmd.Connection.State <> ConnectionState.Open Then cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd = Nothing
Catch ex As Exception
Err.Raise(1000, "EjecutarSP", ex.Message)
End Try
End Sub
thanks
AFAIK the SqlClient doesn't support nameless parameters
From here:
Nameless, also called ordinal, parameters are not supported by the .NET Framework Data Provider for SQL Server.
However, instead of explicitly creating the parameters, you could fetch the parameters for the Proc with DeriveParameters, once you are connected.
Assuming you wish to blindly wish to trust the order of the parameters to match the parameters of the Proc, simply set the .Value of the parameters at the given index.
Dim cmd As New SqlCommand(SP, cnn)
...
SqlCommandBuilder.DeriveParameters(cmd)
For i = 0 To UBound(Parametros)
cmd.Parameters(i).Value = Parametros(i)
Next
Just reset the name to nothing (null) once the parameter has been added, something like this:
For i = 0 To UBound(Parametros)
Param = New SqlParameter("str", Parametros(i))
cmd.Parameters.Add(Param)
Param.ParameterName = Nothing
Next
You don't have to explicity name or type parameters. There are actually a couple of ways to execute stored procs without naming each parameter. Here is one way using Microsoft's old EnterpriseLibrary (which I still like in 2019).
NB: in VB.NET the size of the parameter array is one less than the number of parameters in the stored proc.
Dim dt As System.Data.DataTable
Dim arrParameters(6) As Object
arrParameters(0) = "Hello"
arrParameters(1) = "World"
arrParameters(2) = "Lorem"
arrParameters(3) = "Ipsum"
arrParameters(4) = "Dolor"
arrParameters(5) = "Blabla"
arrParameters(6) = 12345
Try
Dim db As Microsoft.Practices.EnterpriseLibrary.Data.Database = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase("TheNameOfYourConnectionStringInWebConfig")
dt = db.ExecuteDataSet("TheNameOfYourStoredProcedure", arrParameters).Tables(0)
Catch ex As Exception
End Try
I'm a novice VB programmer and I'm sure this solution is trivial, however, I am getting the above error when I try to display the results of one of my Stored Procs in SQL Server which doesn't need any parameters. How can I fix this?
My code excerpt:
Dim SQLCmd as SQLCommand = new SQLCommand()
SQLCmd.CommandText = "Exec AllTableCount"
SQLCmd.CommandType = CommandType.StoredProcedure
SQLCmd.Connection = GlobalFunctions.GlobalF.GetDevSQLServerStoredProcedure(SQLCmd.CommandType)
SQLCmd.ExecuteNonQuery()
MsgBox(SQLCmd.ExecuteNonQuery)
Where GetDevSQLServerStoredProcedure is defined in a different file as:
Public Shared Function GetDevSQLServerStoredProcedure(ByVal SQL As String)
Dim DBConn As SQLConnection
Dim DBCommand As SQLDataAdapter
Dim DSPageData As New System.Data.DataSet
DBConn = New SQLConnection(ConfigurationSettings.AppSettings("AMDMetricsDevConnectionString"))
DBCommand = New SQLDataAdapter(SQL) 'This is the line it errors on'
DBCommand.Fill(DSPageData, "Exceptions")
Return DSPageData
End Function
I can see this SP from VS 2008 in the Server Explorer. So the problem seems to be that I don't know how to connect a data adapter to an SP. Just a string query.
Command text should just be the name of the stored procedure as Tim mentioned.
It looks like the problem you are having now is that you are passinging the CommandType to your method GetDevSQLServerStoredProcedure instead of a string.
I have a small requirement and i request anyone to help me out by providing the source code for the same.
The requirement is as follows:
Can you please help me as to how to call a stored procedure by passing paramenters and populate a CheckListBox in VB.NET based on the results returned from the stored procedure.
Regards,
George
Imports System.Data
Imports System.Data.SqlClient
import that namespace and write the following code to some method and change your code According to your Database and Procedure Fields
'Set up Connection object and Connection String for a SQL Client
Using SQLCon As New SqlClient.SqlConnection
SQLCon.ConnectionString = "Data Source=Server;User ID=User;Password=Password;"
SQLCon.Open()
Dim lDataTable As New DataTable
Using SQLCmdAs New SqlCommand()
SQLCmd.CommandText = "GetAuthors" ' Stored Procedure to Call
SQLCmd.CommandType = CommandType.StoredProcedure
SQLCmd.Connection = SQLCon
SQLCmd.Parameters.Add("AuthorName", SqlDbType.VarChar)
Dim daPubs As New SqlDataAdapter
daPubs.SelectCommand = SQLCmd
daPubs.Fill(lDataTable)
End Using
End Using
CheckBoxList1.DataSource = lDataTable;
CheckBoxList1.DataTextField = "Name";
CheckBoxList1.DataValueField = "ID"
CheckBoxList1.DataBind();
Using Stored Procedures in Conjuction with DataAdapter
How to call SQL Server stored procedures in ASP.NET by using Visual Basic .NET
I've got a sql stored proc that is working fine in SSMS. When I try and execute through code and assign the return to a dataset I am getting zero rows back. I've used the immediate window to ensure that I am sending the correct params to the stored proc and that is all good.
What else would cause me to get zero rows assigned to the dataset. Here is my code.
Thanks,
Mike
EDIT: I'm not getting any exceptions from SQL..
Public Function GetTransReporting(ByVal transNumber As Long, ByVal customerID As Long) As DataCommon.transReporting
Dim myTransReporting As New transReporting
Dim da As SqlDataAdapter
Dim prm1 As SqlParameter
Dim prm2 As SqlParameter
mcmd = New SqlCommand
mcmd.CommandType = CommandType.StoredProcedure
mcmd.Connection = mcn
mcmd.CommandText = "GetTransReportingByCustomerID"
prm1 = New SqlParameter("#transNumber", Data.SqlDbType.BigInt)
prm1.Value = customerID
mcmd.Parameters.Add(prm1)
prm2 = New SqlParameter("#customerNumber", Data.SqlDbType.BigInt)
prm2.Value = transNumber
mcmd.Parameters.Add(prm2)
da = New SqlDataAdapter(mcmd)
da.Fill(myTransReporting)
Return myTransReporting
End Function
Got it.. if you take a look at my parameters up top I am accidentally assigning transaction to customer and customer to transaction. DOH!
Thanks,
Mike
Does your stored procedure start with SET NOCOUNT ON? The lack of this can sometimes cause issues if the stored procedure is processing multiple queries before the final SELECT.