The parameters aren't add to the sql string, what i'm doing wrong?
SqlCommand comando = conexao.CreateCommand();
comando.CommandTimeout = 7200;
foreach (SqlParameter parametro in parametros)
{
comando.Parameters.Add(new SqlParameter(parametro.ParameterName, parametro.Value));
}
comando.CommandText = cmdSql;
comando.CommandType = CommandType.Text;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = comando;
try
{
adapter.Fill(dt);
}
catch (Exception ex) { Console.Write(ex.Message); }
conexao.Close();
return dt;
The Sql String, with the method who call the method above.
string cmdSql = "select top #quantidade * from representante";
SqlParameterCollection sqlParameters = new SqlCommand().Parameters;
sqlParameters.AddWithValue("#quantidade", SqlDbType.Int).Value = quantidade;
return Persistencia.Persistencia.ConsultaComando(cmdSql, sqlParameters);
Thanks for all helping but the solution is use string cmdSql = "select top (#quantidade) * from representante"; was answered in the MSDN:
Answer in MSDN BRASIL
Assign CommandText before adding parameters and show cmdSql content.
On the AddWithValue method you are trying to pass an enum as the parameter value.
Replace this:
sqlParameters.AddWithValue("#quantidade", SqlDbType.Int).Value = quantidade;
With this:
sqlParameters.AddWithValue("#quantidade", quantidade);
Related
I have created one method in data Access class to select data from database with parameter. I just want to use parameterized query.
Method Is :
public DataTable executeSelectQuery(String _query, SqlParameter[] sqlParameter)
{
SqlCommand myCommand = new SqlCommand();
DataTable dataTable = new DataTable();
dataTable = null;
DataSet ds = new DataSet();
try
{
myCommand.Connection = openConnection();
myCommand.CommandText = _query;
myCommand.Parameters.AddRange(sqlParameter);
myCommand.ExecuteNonQuery();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(ds);
dataTable = ds.Tables[0];
}
catch (SqlException e)
{
return null;
}
finally
{
myCommand.Connection = CloseConnection();
}
return dataTable;
}
but I can't understand how to use this method to fetch data and how to pass parameter?
My query may be "select password from tblUsers where email=#email" How to pass #email at business layer?
How to make method in data access class for getting Scalar value?
public string getpasswrd(string unm)
{
con.Open();
string cpaswrd;
cmd1 = new SqlCommand("select password from tbl_login where username='" + unm + "'", con);
cpaswrd = (String)cmd1.ExecuteScalar();
con.Close();
return cpaswrd;
}
SqlParameter param;
cmd1 = new SqlCommand("select password from tbl_login where username=#username, con);
param = new SqlParameter("#username", SqlDbType.VarChar);
param.Direction = ParameterDirection.Input;
param.Value = unm;
cmd1.Parameters.Add(param);
cpaswrd = cmd1.ExecuteScalar().ToString();
You just need to use the same name in the sql parameter:
new SqlParameter("email", "myemail#gmail.com")
I am working on a DbCompre tool. Basically my requirement is that through C#, generate stored procedure script in web application. First of all is it possible?
In SQL Server we generate script easily through right click or with the help of command sp_helptext <ProcedureName>.
Here is my code:
public DataTable generateScripts()
{
SqlCommand cmd = new SqlCommand("sys.sp_helptext dloc_GetTasksRewarehousePutaway", AppCon);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(DS);
adp.SelectCommand = cmd;
return DS.Tables[0];
}
When code execute I am getting this error:
Could not find stored procedure 'sys.sp_helptext dloc_GetTasksRewarehousePutaway'
But in database this procedure is available.
Absolutely its possible, you need to pass the SP name as a parameter though to the parameter objname:-
SqlCommand cmd= new SqlCommand("sys.sp_helptext", AppCon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname", "dloc_GetTasksRewarehousePutaway");
using (SqlConnection con = new SqlConnection ("Connection String Here"))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "sp_helptext #procName";//Stored Procedure name
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("procName", "dloc_GetTasksRewarehousePutaway");
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
/*
You will get the CREATE PROC text here
Do what you need to with it. For example, write
to a .sql file
*/
}
}
}
}
Whole example to get stored procedure T-SQL text from database
// add connection string
var conString = "Db Connection String";
// add SP name
var spName = "DbSpName";
var sb = new StringBuilder();
try
{
using (var conn = new SqlConnection(conString))
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("sys.sp_helptext", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname",spName );
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
sda.SelectCommand = cmd;
var dt = ds.Tables[0];
foreach (DataRow dtRow in dt.Rows)
{
sb.Append(dtRow["Text"].ToString());
}
}
}
catch (Exception ex)
{
// log if something went wrong ex.Message
}
I have the following code:
public DataTable opencon(PAL.property objpal)
{
string query = "Select UserId,Firstname,UserType from TBL_USER_LOGIN where Username=#username and Password=#password and Status=1";
OleDbCommand objcmd = new OleDbCommand();
objcmd.CommandText = query;
objcmd.Connection = oldbcon;
oldbcon.Open();
objcmd.Parameters.Add("#username", OleDbType.VarChar).Value = objpal.username;
objcmd.Parameters.Add("#password", OleDbType.VarChar).Value = objpal.Password;
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter(objcmd);
adp.Fill(dt);
return dt;
}
Here I want to fetch some values from the table according to a condition,
but when I run this code it shows the following error:
Even though I passed the correct parameters value in #username and #password. How can I resolve this error? Please help.
Try This:
public DataTable opencon(PAL.property objpal)
{
string query = "Select UserId,Firstname,UserType from TBL_USER_LOGIN where Username=? and Password=? and Status=1";
OleDbCommand objcmd = new OleDbCommand();
objcmd.CommandText = query;
objcmd.Connection = oldbcon;
oldbcon.Open();
objcmd.Parameters.Add("#username", OleDbType.VarChar).Value = objpal.username;
objcmd.Parameters.Add("#password", OleDbType.VarChar).Value = objpal.Password;
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter(objcmd);
adp.Fill(dt);
return dt;
}
Try This
string query = "Select [UserId],[Firstname],[UserType] from [TBL_USER_LOGIN] where [Username]=? and [Password]=? and [Status]=1";
i'm trying to invoke an Oracle function that returns a type encapsulated in a Table
Type Object
create or replace
type Z_TBL_STRUCTURE_CODE
AS OBJECT
(
PROJ_ID varchar2(50 BYTE)
);
Type table
create or replace
type Z_TABLE_STRUCTURE_CODE AS TABLE of Z_TBL_STRUCTURE_CODE;
Oracle Function
create or replace
FUNCTION Z_TESTE_IN_FUNC
(
var_teste in varchar2
)
return Z_TABLE_STRUCTURE_CODE
AS
tab Z_TABLE_STRUCTURE_CODE;
BEGIN
EXECUTE IMMEDIATE
'SELECT
CAST(
MULTISET(
select count(*) into num from structure
where structure_code in ('|| var_teste ||')) as Z_TABLE_STRUCTURE_CODE)
into tab
from dual;';
dbms_output.put_line(var_teste);
return tab;
END Z_TESTE_IN_FUNC;
NOTE: PLEASE IGNORE THE EXECUTE IMMEDIATE, ITS JUST FOR A TEST.
NOTE2: I KNOW THERE IS AN OPTION TO AVOID TYPES (USING CURSORS) BUT I HAVE NOT YET BEEN ABLE TO UNDERSTAND THE TOPIC SO I WOULD ASK YOU TO IGNORE CURSOS WHEN ANSWERING, UNLESS ITS THE ONLY OPTION AVAILABLE.
C# Code
public DataTable getTaskStartFinish()
{
OleDbConnection con = null;
OleDbDataReader reader = null;
try{
con = new OleDbConnection(ConfigurationManager.ConnectionStrings["OracleBD"].ConnectionString);
OleDbCommand cmd = new OleDbCommand("", con);
cmd.CommandText = "Z_TESTE_IN_FUNC";
cmd.CommandType = CommandType.StoredProcedure;
OleDbParameter retval = new OleDbParameter("retval", OleDbType.VarChar, 10);
retval.Direction = ParameterDirection.ReturnValue;
OleDbParameter inval = new OleDbParameter("inval", OleDbType.Variant, 50);
inval.Direction = ParameterDirection.Input;
inval.Value = "1";
cmd.Parameters.Add(retval);
cmd.Parameters.Add(inval);
con.Open();
reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
return dt;
}
catch(Exception ex)
{
throw new Exception("getTaskStartFinish error: " + ex.Message);
}
finally
{
if(con != null)
con.Close();
if(reader != null || !reader.IsClosed)
reader.Close();
}
}
The current Error i get is the following:
ORA-06550: line 1, column 13:
PLS-00382: expression is of wrong type
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
I have seen in the net similar examples but all using ExecuteScalar() or some code for procedures or function returning singular values but not tables.
Well if you want to return a single value my suggestion is(Edited for multiple rows):
OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["OracleBD"].ConnectionString);
OleDbCommand cmd = new OleDbCommand("Z_TESTE_IN_FUNC", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#procValueName", "myValue");
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
conn.Open();
try
{
da.Fill(dt);
}
catch (Exception excp)
{
//Handle Exception
}
finally
{
conn.Close();
}
Edit 2: Try this for function
OleDbConnection con = new OleDbConnection(cntStr);
con.Open();
OleDbCommand cmd = new OleDbCommand("F_TESTFUNC", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OleDbParameter("retVal", OleDbType.VarChar, 11,ParameterDirection.ReturnValue, true, 0, 0, "retVal", DataRowVersion.Current,null);
cmd.Parameters.Add("ID", strID);
cmd.ExecuteScalar();
con.Close();
I created a stored procedure so as to return me a table.
Something like this:
create procedure sp_returnTable
body of procedure
select * from table
end
When I call this stored procedure on the frontend what code do I need to write to retrieve it in a datatable object?
I wrote code something like the following. I basically want to know retrieving and storing table into an object of datatable. All my queries are running, but I don't know how to retrieve table into a datatable through a stored procedure
DataTable dtable = new DataTable();
cmd.Connection = _CONN;
cmd.CommandText = SPNameOrQuery;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
OpenConnection();
adp.Fill(dtTable);
CloseConnection();
Here in this code a command has been bound with the stored procedure name and its parameters. Will it be returning me a datatable from the stored procedure?
string connString = "<your connection string>";
string sql = "name of your sp";
using(SqlConnection conn = new SqlConnection(connString))
{
try
{
using(SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = new SqlCommand(sql, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds, "result_name");
DataTable dt = ds.Tables["result_name"];
foreach (DataRow row in dt.Rows) {
//manipulate your data
}
}
}
catch(SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch(Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
Modified from Java Schools Example
Set the CommandText as well, and call Fill on the SqlAdapter to retrieve the results in a DataSet:
var con = new SqlConnection();
con.ConnectionString = "connection string";
var com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "sp_returnTable";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
(Example is using parameterless constructors for clarity; can be shortened by using other constructors.)
Explaining if any one want to send some parameters while calling stored procedure as below,
using (SqlConnection con = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(storedProcName, con))
{
foreach (var item in sqlParams)
{
item.Direction = ParameterDirection.Input;
item.DbType = DbType.String;
command.Parameters.Add(item);
}
command.CommandType = CommandType.StoredProcedure;
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(dt);
}
}
}