I have the following stored procedure:
CREATE PROCEDURE MyProc
#posted_xml_body xml
AS
INSERT INTO MyTable
(post_datetime, post_body)
VALUES
(getdate(), #posted_xml_body)
And the following VB code:
Using aConnection As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings(connectionString).ConnectionString)
aConnection.Open()
Dim aCommand As New Data.SqlClient.SqlCommand("MyProc", aConnection)
aCommand.CommandType = Data.CommandType.StoredProcedure
aCommand.Parameters.AddWithValue("#posted_xml_body", aXMLString)
Dim rows_affected As Integer = aCommand.ExecuteNonQuery()
aCommand.Dispose()
aConnection.Close()
Return rows_affected
End Using
However, I keep receiving the following error
"Procedure or function has too many arguments specified."
Thanks for any suggestions.
You pasted wrong or is missing a ")" here
VALUES
(getdate(), #posted_xml_body)
There are couple things I would suggest.
chang the column type to nvarchar(max), select scope identity, just make sure your table as a primary key because you vb code will give you an exception trying to convert date to integer.
CREATE PROCEDURE MyProc
#posted_xml_body as nvarchar(max)
AS
Begin
INSERT INTO MyTable
(post_datetime, post_body)
VALUES
(getdate(), #posted_xml_body);SELECT SCOPE_IDENTITY()
END
Your Vb Code
Using aConnection As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings(connectionString).ConnectionString)
Dim rows_affected As Integer = 0
Try
aConnection.Open()
Dim aCommand As New Data.SqlClient.SqlCommand("MyProc", aConnection)
aCommand.CommandType = Data.CommandType.StoredProcedure
aCommand.Parameters.AddWithValue("#posted_xml_body", aXMLString)
rows_affected = aCommand.ExecuteScalar()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
If aConnection.State = ConnectionState.Open Then
aConnection.Close()
End If
End Try
Return rows_affected
End Using
Related
I am just new in oracle and using procedure and still learning, but I have a problem how can I populate the combo box using store procedure? I already have a code but when I run it, it shows an error IndexOutOfRangedException was unhandled and Cannot find Column 1.
Here's my code
(Procedure/Oracle Sql:)
procedure cmbbox_location (o_output out o_refcur)
as
o_cur o_refcur;
begin
open o_cur for
select city_id, city_name from city;
o_output := o_cur;
end cmbbox_location;
(program/vb.net)
Private Sub Main_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
instantiate_dev()
ora_conn.Open()
populate_cmbbox_loc()
End Sub
Private Sub populate_cmbbox_loc()
instantiate_dev()
ora_conn.Open()
qr.populate_location()
cmblocation.DataSource = dt
cmblocation.ValueMember = dt.Columns(0).ColumnName
cmblocation.DisplayMember = dt.Columns(1).ColumnName
cmblocation.Text = ""
cmblocation.SelectedIndex = 0
End Sub
Public Function populate_location()
dt = New DataTable
bg.GetProcDataTable(connStr, "Location_Package.cmbbox_location")
cmd.Parameters.Add(New OracleParameter("O_OUTPUT", OracleDbType.RefCursor)).Direction = ParameterDirection.Output
adap_or.SelectCommand = cmd
adap_or.Fill(dt)
Return dt
ora_conn.Close()
End Function
The error you are getting indicates that you are indexing something that doesn't exist, it's possible/probable your stored procedure isn't returning anything. To address William Robertson's concern about the ref cursor:
There are any number of ways to output a ref cursor. The one I use the most is a ref cursor type defined in the package definition, for example:
CREATE OR REPLACE PACKAGE Location_Package IS
TYPE DataOutCursor IS REF CURSOR;
procedure cmbbox_location (o_output out DataOutCursor);
END Location_Package;
/
Then in the procedure in the package body:
CREATE OR REPLACE PACKAGE BODY Location_Package IS
procedure cmbbox_location (o_output out DataOutCursor) as
begin
open o_output for
select city_id, city_name from city;
end;
END;
/
I assume the error is occurring here:
cmblocation.ValueMember = dt.Columns(0).ColumnName
cmblocation.DisplayMember = dt.Columns(1).ColumnName
It is always best to make sure the data table has data first so wrap the combo box lines with:
IF dt.Rows.Count > 0 Then
' ..... assign the data table to the combo box
Else
' Some error message ...
End IF
This will get rid of the unhandled exception and help you to figure out the issue.
On last thing, your function needs to return a value (datatable):
Public Function populate_location() as Datatable
dt = New DataTable
bg.GetProcDataTable(connStr, "Location_Package.cmbbox_location")
cmd.Parameters.Add(New OracleParameter("O_OUTPUT", OracleDbType.RefCursor)).Direction = ParameterDirection.Output
adap_or.SelectCommand = cmd
adap_or.Fill(dt)
Return dt
ora_conn.Close()
End Function
I'm working in asp.net with vb.net and in the backend I'm trying to select something from the database.
But whenever I ask to execute the query it gives an error which says 'OverflowException Ocuured'. The query that is made works perfectly in my SQL Manager tool. Any ideas what can be the problem.
(it gives the problem on the line under 'try' so the 'returnedId = com.ExecuteScalar' line)
Function selectEIDCardnumber(ByVal name As String) As Integer
Dim con As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("testdatabase").ConnectionString)
Dim selecter As String = "SELECT EIDCardNumber FROM [dbo].[_User] where DisplayName = #name"
Dim com As New SqlCommand(selecter, con)
com.Parameters.AddWithValue("#name", name)
con.Open()
Dim returnedId As Integer = 0
Try
returnedId = com.ExecuteScalar
Catch ex As Exception
Response.Redirect("oops.aspx")
End Try
con.Close()
Return returnedId
End Function
The result of com.ExecuteScalar is larger than the max int value.
Int32.TryParse(com.ExecuteScalar, returnedId)
By defining your returnedId and Function As type Integer you are telling VB that the value will be a whole number between -2,147,483,648 and 2,147,483,647. Assuming the data in your database is correct, the solution is to change the returnedId and Function types to Int64, which holds numbers up to 9,223,372,036,854,775,807.
If you're sure that the EIDCardNumber column is an integer type column then try changing Dim returnedId As Integer = 0 into Dim returnedId As Long = 0 and if the problem persists try changing the value of selecter to "SELECT top 1 EIDCardNumber FROM [dbo].[_User] where DisplayName = #name"
I've been trying to figure out this bug for a while now, some help would be appreciated. Thanks.
Here is my error message:
Procedure or function 'getAvailableSMSNumbers' expects parameter '#Election_ID', which was not supplied.
Here is my sql code:
CREATE PROCEDURE {databaseOwner}{objectQualifier}getAvailableSMSNumbers
#Election_ID nvarchar(20)
AS
SELECT *
FROM {databaseOwner}{objectQualifier}icc_sms_phones
LEFT JOIN {databaseOwner}{objectQualifier}icc_sms_elections ON sms_elections_sms_number = phones_number
WHERE sms_elections_sms_number IS NULL
OR sms_elections_id = #Election_ID
GO
Function:
Public Overrides Function getAvailableSMSNumbers(eventid As String) As IDataReader
Dim dtable As New DataTable
Using sqlconn As New SqlConnection(Me.ConnectionString)
Using sqlcomm As New SqlCommand
Using sqlda As New SqlDataAdapter
sqlcomm.Connection = sqlconn
sqlcomm.CommandType = CommandType.StoredProcedure sqlcomm.CommandText=GetFullyQualifiedName("getAvailableSMSNumbers")
sqlcomm.Parameters.AddWithValue("#Election_ID", eventid)
sqlda.SelectCommand = sqlcomm
sqlconn.Open()
sqlda.Fill(dtable)
sqlconn.Close()
Return dtable.CreateDataReader
End Using
End Using
End Using
End Function
Where the function is used:
Public Function getAvailableSMSNumbers(eventid As String) As List(Of phoneModel)
Dim numbers As New List(Of phoneModel)
Dim number As phoneModel
numbers = CBO.FillCollection(Of phoneModel)(dal.getAvailableSMSNumbers(eventid))
For Each number In numbers 'dal.getAvailableSMSNumbers(eventid).Rows
number = New phoneModel
With number
.val = ("PHONES_NUMBER").ToString
.text = String.Format("{0:# (###) ###-####}", Long.Parse(.val))
End With
numbers.Add(number)
Next
Return numbers
End Function
If you need anymore information, let me know, and I will add it.
This typically occurs if the object supplied as the value of your SQL parameter is NULL, but the stored procedure does not allow null values (which yours does not). You can set a conditional breakpoint on this line sqlcomm.Parameters.AddWithValue("#Election_ID", eventid) to make sure the eventid parameter is not null.
It might also be a good idea to use defensive coding, and in your getAvailableSMSNumbers function, check to make sure eventid is not null, and if it is, throw an exception or provide some type of feedback for the user.
As an option you can try to re-compile your stored procedure to allow NULL parameter :
CREATE PROCEDURE {databaseOwner}{objectQualifier}getAvailableSMSNumbers
#Election_ID nvarchar(20) = NULL
AS
That means that the default value of your Parameter will be null in case there is no value on input. This solution will be nice in case you want to return empty datatable without error. In any other case you have to debug your VB code and understand where the issue starts.
Think about how you are calling you procedure. When you call you need to supply the value of the procedure: For example,
Call get_particular_girl_from_girlsTable("Jane")
where get_particular_girl_from_girlsTable is the procedure and "Jane" is value for parameter GirlName.
Did you verify if
cmd.CommandType = CommandType.**StoredProcedure**
By default, the value is Text, expecting a SELECT, INSERT or other command text.
I deliberately trigger a SqlException in the following insert statement in the code below and replaced the correct column name ModifiedBy by ModifiedB
You need to wrap the entire SQL Code in a transaction. Take this example:
create table errTest
(
intVal int
)
insert into errTest select 1
insert into errTest select 1/0
select * from errTest --one record
The second insert fails, but since no transaction was explicitly started, each insert is inherently its own transaction. The first succeeds, the second fails, and the table ends up retaining the successful insert.
If all inserts are wrapped in a transaction, and if xact_abort is on, then any error thrown by any insert will cause the entire transaction to rollback:
create table errTest
(
intVal int
)
set xact_abort on
begin transaction
insert into errTest select 1
insert into errTest select 1/0
commit transaction
select * from errTest --zero records
You need to pass your transaction and connection to all your commands you wish to use inside a SQL transaction, this is my example (I cut some things out using notepad so it might give errors in studio)
Private Sub main()
Using sql_conn
sql_conn.Open()
Dim SQL_transaction_INPUT As SqlClient.SqlTransaction = sql_conn.BeginTransaction
Try
Dim isOK as Boolean = False
isOK = update_BSE(myID, sql_conn, SQL_transaction_INPUT)
If isOK Then
SQL_transaction_INPUT.Commit()
sql_conn.Close()
Else
SQL_transaction_INPUT.Rollback()
sql_conn.Close()
End If
Catch ex As Exception
SQL_transaction_INPUT.Rollback()
If sql_conn.State = ConnectionState.Open Then sql_conn.Close()
End Try
End Using
End Sub
Private Function update_BSE(ByVal _IDmod As Integer, _
ByVal conn_with_trans As SqlConnection, _
ByVal conn_transaction As SqlTransaction) As Boolean
Dim ins As String = "UPDATE something WHERE IDrec = #IDmod"
Dim cmdINS As New SqlCommand(ins, conn_with_trans, conn_transaction)
Try
With cmdINS.Parameters
.Add("IDmod", SqlDbType.Int).Value = _IDmod
End With
cmdINS.ExecuteNonQuery()
Return True
Catch ex As Exception
Return False
End Try
End Function
read a lot about DataAdapter, DataTable ,.. to reach to this code, in the Save Button:
'insert new row
ds.Tables("Employees").Rows.Add(ENumTxt.Text, ENameTxt.Text, EPosTxt.Text,
EAgeTxt.Text, ESalTxt.Text, EPhonTxt.Text, EAdrsTxt.Text)
'save changes
ds.AcceptChanges()
Try
If ds.HasChanges Then
Dim AffectedDS As DataSet = ds.GetChanges(DataRowState.Added)
'im ComBuilder As New OleDb.OleDbCommandBuilder(da)
da.InsertCommand = ComBuilder.GetInsertCommand
da.Update(AffectedDS, "Employees")
End If
Catch e1 As OleDb.OleDbException
MessageBox.Show(e1.Message)
End Try
===============================================================================
Then I tried this:
Dim cb As New OleDb.OleDbCommandBuilder(da)
' Insert a new record in the DataSet
Dim r As DataRow = ds.Tables("Employees").NewRow()
r("EID") = ENumTxt.Text
r("EName") = ENameTxt.Text
r("Age") = EAgeTxt.Text
r("Salary") = ESalTxt.Text
r("EPhone") = EPhonTxt.Text
r("EAddress") = EAdrsTxt.Text
ds.Tables("Employees").Rows.Add(r)
' Insert the record even in the database
da.Update(ds.Tables("Employees").GetChanges())
' Align in-memory data with the data source ones
ds.AcceptChanges()
==========
In run time, i got the same error message for both cases
"Syntax error in INSERT INTO statement"
Please give me some guidlines to fix this error.
Ther error is in your INSERT statement, as the error says ...
How does the INSERT statement that has been specified by the 'InsertCommand' of your DataAdapter look like ?
The only thing that comes to mind is if using the Commandbuilder, does your table have a primary key defined?