I have a problem passing an array parameter using c#, my code is:
private OracleDataAdapter da;
private OracleConnection cnn;
public DataTable select_ids_between_friends(int cod, List<int> excludeList) {
DataTable dt = new DataTable();
try
{
using (cnn = new OracleConnection(Properties.Settings.Default.connectionString1))
{
cnn.Open();
da = new OracleDataAdapter("PROC_SELECT_IDS_BT_FRIENDS", cnn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("CURSOR", OracleDbType.RefCursor, ParameterDirection.Output);
da.SelectCommand.Parameters.Add("COD_US", OracleDbType.Int32, cod, ParameterDirection.Input);
da.SelectCommand.Parameters.Add(new OracleParameter("IDS_FRIEND", OracleDbType.Int32));
da.SelectCommand.Parameters[2].CollectionType = OracleCollectionType.PLSQLAssociativeArray;
da.SelectCommand.Parameters[2].Value = excludeList.ToArray();
da.SelectCommand.Parameters[2].Size = excludeList.Count;
da.Fill(dt);
cnn.Close();
}
}
catch (Exception ex)
{
}
return dt;
}
in the database I created the array and the stored procedure like this:
This is the Oracle type:
CREATE TYPE FACEBOOK.ARRAY_ID_FRIENDS AS TABLE OF INT;
Finally this is my procedure:
CREATE OR REPLACE PROCEDURE PROC_SELECT_IDS_BT_FRIENDS
(DATA_CURSOR OUT SYS_REFCURSOR,COD_US IN INT, IDS_FRIEND IN FACEBOOK.ARRAY_ID_FRIENDS) IS
BEGIN
OPEN DATA_CURSOR FOR
SELECT ID_USER1,ID_USER2 FROM T_FRIENDSHIP WHERE ID_USER2 NOT IN(SELECT COLUMN_VALUE FROM TABLE(IDS_FRIEND)))
END;
/
The error showed is PLS-00306: wrong number or types of arguments in call PROC_SELECT_IDS_BT_FRIENDS. Please help me. Thanks in advance.
This line:
da.SelectCommand.Parameters.Add(new OracleParameter("IDS_FRIEND", OracleDbType.Int32));
Why is it an Int32? Shouldn't it be an array? I see that you declare it as an array, but only till later. Is there a different way to declare it?
Related
The code below sends the values entered in the text box to the oracle database in a list
And this list call oracle procedure.
I would like to send the values returned from this list into a gridview.
public void gridDoldur()
{
var seciliProsedur = "Z_LABEL_PRINTER.LabelPieceList";
List<string> gridList = OraclePieceList();
using (OracleConnection con = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand(seciliProsedur, con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("p_piece_id", OracleDbType.Varchar2).Value = gridList;
cmd.Parameters.Add("p_rc",OracleDbType.RefCursor).DirectionParameterDirection.Output;
OracleDataAdapter da = new OracleDataAdapter(cmd);
OracleCommandBuilder commandBuilder = new OracleCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
this.gridPieceList.Visible = true;
gridPieceList.DataSource = dt;
}
conn.Close();
}
public List<string> OraclePieceList()
{
List<string> pieces = new List<string>();
for (int i = 0; i < txtListe.Lines.Count(); i++)
{
pieces.Add(txtListe.Lines[i]);
}
return pieces;
}
Oracle Procedure :
Declaration
CREATE OR REPLACE PACKAGE Z_LABEL_PRINTER
AS
TYPE t_piece_id IS TABLE OF piece.PIECE_ID %type index by pls_integer;
PROCEDURE LabelPieceList (p_piece_id IN t_piece_id,
p_rc IN OUT sys_refcursor);
END Z_LABEL_PRINTER;
Body :
CREATE OR REPLACE PACKAGE BODY .Z_LABEL_PRINTER
AS
PROCEDURE LabelPieceList(p_piece_id IN t_piece_id,
p_rc IN OUT sys_refcursor)
as
BEGIN
OPEN p_rc FOR
SELECT * FROM piece WHERE PIECE_ID IN (SELECT * FROM TABLE(p_piece_id));
END;
-- Package body
END Z_LABEL_PRINTER;
But i encountered this error :
ORA-06550: line 1, column 7: PLS-00306: wrong number or types of
arguments in call to 'LabelPieceList'
I'm new to using SqlDataAdpter and I'm trying to execute a stored procedure. The stored procedure executes successfully but no rows are returned. I've used SQL Server Profiler to monitor the call and it runs successfully (I can copy and execute the query from profiler without modifying it and get results).
I have the following:
public ActionResult Index()
{
SqlConnection conn = null;
DataSet results = null;
try
{
string connectionString = // ... my connection
conn = new SqlConnection(connectionString );
string query = #"usp_mySP";
conn.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter(query, conn);
sqlAdpt.SelectCommand.CommandType = CommandType.StoredProcedure;
var dataDate = new SqlParameter { ParameterName = "#DataDate", Value = DateTime.Now };
var idList = new SqlParameter { ParameterName = "#IDList", Value = "1231,2324,0833" };
sqlAdpt.SelectCommand.Parameters.Add(dataDate);
sqlAdpt.SelectCommand.Parameters.Add(idList);
results = new DataSet();
sqlAdpt.Fill(results);
sqlAdpt.Dispose();
}
catch (SqlException e)
{
throw new Exception("Exception:" + e.Message);
}
finally
{
if (conn != null)
conn.Close();
}
return View(results);
}
When I inspect the DataSet through the debugger, it always returns 0 rows.
Please help with what I'm doing wrong?
Note: I've also tried (but do NOT prefer) executing as a SQL command:
EXEC usp_mySP #DataDate, #IDList
and it didn't work either as I got int to varchar conversion errors.
I think you try to add SqlParameter using SqlCommand like this :
SqlCommand cmd = new SqlCommand();
cmd.parameter.addwithvalue(#DataDate,DateTime.Now);
So the reason was because of set nocount on. I added it to my sp and it works. Thank you everyone for clarifying.
I have used following stored procedure in sql:
alter procedure [dbo].[usp_Member_Org_OnGoingJobs]
(
#idUser varchar(50)
)
as
begin
declare #qry as varchar(max)
set #qry='select J.idJob,j.DateAdded,j.OpenedByWho,j.JobAddress ,j.final,j.idOrg,j.note
from Job J
inner join Users U on
U.idOrg=J.idOrg
where U.IdUser='+ #idUser+ '
and ISNULL(j.Final,'')=''
order by idJob'
execute(#qry)
end
GO
This stored procedure is formed sucessfully in sql.
But, When i tried to use them through asp.net c#, It gives me error:
Incorrect syntax near the keyword 'order'.
Everything seems correct.
Please tell me where i am making mistake??
Edit:
private void BindOnGoingJobs()
{
string sqlOnGoingJobs = "usp_Member_Org_OnGoingJobs";
DataTable dtJobList = new DataTable();
ArrayList paramList = new ArrayList();
paramList.Add(new ParamData("#idUser", Convert.ToString(Session["idUser"])));
dtJobList = obj.ExecuteProcedureAndGetDataTable(sqlOnGoingJobs, paramList);
grdOnGoingJobs.DataSource = dtJobList;
grdOnGoingJobs.DataBind();
paramList.Clear();
}
public DataTable ExecuteProcedureAndGetDataTable(string procedureName, ArrayList Parameters)
{
DataTable dt = new DataTable();
try
{
if (con.State != ConnectionState.Open)
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = procedureName;
cmd.Parameters.Clear();
foreach (ParamData p in Parameters)
{
cmd.Parameters.AddWithValue(p.pName, p.pValue);
}
da.SelectCommand = cmd;
da.Fill(dt);
con.Close();
return dt;
}
catch (Exception ex)
{
con.Close();
return dt;
}
}
You need to double your single quotes around the ISNULL check
set #qry='select J.idJob,j.DateAdded,j.OpenedByWho,j.JobAddress ,j.final,j.idOrg,j.note
from Job J
inner join Users U on
U.idOrg=J.idOrg
where U.IdUser='+ #idUser+ '
and ISNULL(j.Final,'''')=''''
order by idJob'
You need to escape the quotation mark by placing quotes 2 times like this.
and ISNULL(j.Final,'''')=''''
Check this blog post http://blog.sqlauthority.com/2008/02/17/sql-server-how-to-escape-single-quotes-fix-error-105-unclosed-quotation-mark-after-the-character-string/
Just add the table alias in order by, I guess should solve the issue
order by J.idJob
I have created a Windows Forms application in C# that will make use of a procedure in Oracle database.
In this form there is a DataGridView that I intend to bring the data through this procedure, but do not know what is missing in my code for this function, since it does not bring me any data. Below is the code of both:
Oracle procedure:
PROCEDURE P_TRANSFITENS(vID in NUMBER) is
cursor vAUX is
select t.pro_in_codigo,
t.alm_in_codigo,
t.loc_in_codigo,
u.loc_st_nome,
t.nat_st_codigo,
t.mvs_re_quantidade,
t.mvs_st_loteforne
from bd.est_movsumarizado t, bd.est_almoxlocal u
where t.pro_in_codigo = vID
and u.loc_in_codigo = t.loc_in_codigo;
rDadosItem vAUX%ROWTYPE;
begin
open vAUX;
loop
fetch vAUX
into rDadosItem;
exit when vAUX%NOTFOUND;
end loop;
close vAUX;
end;
C# (Button click handler):
OracleDataAdapter adp = new OracleDataAdapter();
OracleConnection objConn = new OracleConnection();
objConn.ConnectionString = "Data Source=dtsource;User Id=user;Password=pass";
objConn.Open();
adp.SelectCommand = new OracleCommand();
adp.SelectCommand.Connection = objConn;
adp.SelectCommand.CommandText = "P_TRANSFITENS";
adp.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
adp.SelectCommand.Parameters.Add("#vID", Convert.ToInt32(mskdId.Text));
DataTable dt = new DataTable();
adp.Fill(dt);
dtgrvDetalhesItem.DataSource = dt;
Thanks a lot!
P.S.: Sorry for my bad english.
I think the format should be like
PROCEDURE P_TRANSFITENS(vID in NUMBER, _RESULTS OUT SYS_REFCURSOR)
IS
BEGIN
OPEN _RESULTS FOR
select t.pro_in_codigo,
t.alm_in_codigo,
t.loc_in_codigo,
u.loc_st_nome,
t.nat_st_codigo,
t.mvs_re_quantidade,
t.mvs_st_loteforne
from bd.est_movsumarizado t, bd.est_almoxlocal u
where t.pro_in_codigo = vID
and u.loc_in_codigo = t.loc_in_codigo;
END P_TRANSFITENS;
Then you add this
cmd.CommandType = CommandType.StoredProcedure;
OracleParameter refcursor = new OracleParameter("_RESULTS", OracleDbType.RefCursor);
refcursor.Direction = ParameterDirection.Output;
cmd.Parameters.Add(refcursor);
It seems to me that you aren't configure input/output params correctly.
try something like this:
OracleParameter param = cmd.Parameters.Add("vAUX", OracleDbType.RefCursor);
param.Direction = ParameterDirection.Output;
OracleParameter param2 = cmd.Parameters.Add("vID", OracleDbType.Int32);
param2.Direction = ParameterDirection.Input;
i'm unable to test it, but maybe, give it a try.
ALTER PROCEDURE dbo.SP_InsertTicket
/*
(
#parameter1 int = 5,
#parameter2 datatype OUTPUT
)
declare #i as numeric
exec SP_InsertTicket 'asd','cd#y.com','232323','dasasd','sdasdas','01-jan-2010',#i output,'sdas','sdasd','02-jan-2010'
select #i*/
#Client_FullName varchar(30),
#Client_EmailAdd varchar(50),
#Client_Telephn varchar(15),
#Ticket_Subject varchar(50),
#Ticket_Source varchar(15),
#Ticket_CreateDate Datetime,
#Ticket_Id integer output,
#Que_Message varchar(100),
#Que_Attachment varchar(max),
#Que_UpdateDate Datetime
AS
declare #TickID integer;
/* SET NOCOUNT ON */
BEGIN
INSERT INTO tbl_Ticket (Client_FullName,Client_EmailAdd,Client_Telephn,Ticket_Subject,Ticket_Source,Ticket_CreateDate)
VALUES (#Client_FullName, #Client_EmailAdd ,#Client_Telephn,#Ticket_Subject,#Ticket_Source,#Ticket_CreateDate)
Select #TickID = MAX(Ticket_Id) from tbl_Ticket
set #Ticket_Id=#TickID
INSERT INTO tbl_TicketQuestion (Ticket_Id,Que_Message,Que_Attachment,Que_UpdateDate)
VALUES (#TickID,#Que_Message,#Que_Attachment,#Que_UpdateDate)
END
RETURN
This is my store procedure in which i need to return Ticket_Id to send it via email app
It insert records well bt not able to retirn value in DAL
Below is the code for executing stored procedure which returns value
public class cls_DAL
{
public cls_DAL()
{
//
// TODO: Add constructor logic here
//
}
static string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString();
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
public int insert_NewTicket(string fullname, string emailadd, string telephone, string subject, string source, DateTime date,string Message, string attachment, DateTime updatedate)
{
try
{
con.Open();
cmd = new SqlCommand("SP_InsertTicket", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Client_FullName", fullname);
cmd.Parameters.AddWithValue("#Client_EmailAdd", emailadd);
cmd.Parameters.AddWithValue("#Client_Telephn",telephone);
cmd.Parameters.AddWithValue("#Ticket_Subject", subject);
cmd.Parameters.AddWithValue("#Ticket_Source",source);
cmd.Parameters.AddWithValue("#Ticket_CreateDate",date);
cmd.Parameters.AddWithValue("#Ticket_Id",0);
cmd.Parameters.AddWithValue("#Que_Message", Message);
cmd.Parameters.AddWithValue("#Que_Attachment", attachment);
cmd.Parameters.AddWithValue("#Que_UpdateDate",updatedate);
cmd.Parameters["#Ticket_Id"].Direction = ParameterDirection.InputOutput;
return cmd.ExecuteNonQuery();
int i = (int)cmd.Parameters["#Ticket_Id"].Value;
}
catch
{
throw;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
}
Its just a guess, not sure. You can give a try the following:
cmd.Parameters["#Ticket_Id"].Direction = ParameterDirection.InputOutput;
TO
cmd.Parameters["#Ticket_Id"].Direction = ParameterDirection.Output;
That won't compile you'll get unreachable code
cmd.Parameters["#Ticket_Id"].Direction = ParameterDirection.InputOutput; cmd.ExecuteNonQuery();
return (int)cmd.Parameters["#Ticket_Id"].Value;
or #Matt's solution below...
That cast is iffy as well...
And in a multi user scenario, ticketid will race.
Think about what could (will!!!) happen if you run two of these at the same time
Should be wrapped in a transaction.
And you don't need Max, either, Use Scope_Identity
You could run Select Scope_Identity() after the Insert statement. Then in your DAL Method return Convert.ToInt32(cmd.ExecuteScalar())
Change this:
return cmd.ExecuteNonQuery();
to
Int i = cmd.ExecuteScalar();
If you are only returning one integer from that procedure.
ExecuteNonQuery() isnt the method you want to be using here