I am not getting filled dataset after executing a stored procedure.
protected void btnsub_Click(object sender, EventArgs e)
{
ArrayList arInsert = ReturnParameter_insert();
DataSet dsInsertProfile = objadmin.GetGridData(arInsert, objconstant.sSP_INSERT_PROFILE);
if(int.Parse(dsInsertProfile.Tables[0].Rows[0].ItemArray[0].ToString())== 0)
{
lblThank.Text = "Your profile have been successfully saved.";
}
else
{
lblThank.Text = "Your profile is not saved, please try again later.";
}
}
public ArrayList ReturnParameter_insert()
{
ArrayList arProfile = new ArrayList();
Object[] c_first_name = new object[3] { "#strFname", "Varchar", (txtfname.Text != "") ? txtfname.Text : "" };
arProfile.Add(c_first_name);
return arProfile;
}
public DataSet GetGridData(ArrayList dbArray, string sSpName)
{
DataSet dsDataSet = new DataSet();
dsDataSet = datamanager.GetGridData(dbArray, sSpName);
return dsDataSet;
}
public static SqlDbType GetSqlDataType(string sDataType)
{
return (sDataType == "Integer") ? SqlDbType.Int : (sDataType == "Varchar") ? SqlDbType.VarChar : (sDataType == "Date") ? SqlDbType.Date : SqlDbType.BigInt;
}
public static DataSet GetGridData(ArrayList dbArray, string sSpName)
{
DataSet dsDataSet = new DataSet();
SqlConnection cn = createConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sSpName;
object objPrMtrName;
object objSqlType;
object objPrMtrVal;
int i;
for (i = 0; i < dbArray.Count; i++)
{
objPrMtrName = ((object[])(dbArray[i]))[0];
objSqlType = ((object[])(dbArray[i]))[1];
objPrMtrVal = ((object[])(dbArray[i]))[2];
cmd.Parameters.Add(objPrMtrName.ToString(), GetSqlDataType(objSqlType.ToString())).Value = objPrMtrVal;
}
cmd.Connection = cn;
try
{
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dsDataSet);
return dsDataSet;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cn.Close();
cn.Dispose();
}
}
My stored procedure:
CREATE Procedure spInsert_profile
(#strFname varchar(200))
AS
BEGIN
INSERT INTO gdt_Users([c_first_name], [d_modified_dttm], [d_created_dttm])
VALUES(#strFname, GETDATE(), GETDATE())
END
Here I am using 3 tier, the same methods are working successfully for other pages but not for this particular code. The dataset in GETGRIDDATA method is filling null value. I am not able to find. Please help me....
you performing insert operation in your procedure than how is going to return to data Insert into statement does insert operation not retrieve operation.
...To retrieve data you need to call procedure with select * statement.
There is no select statement in your stored proc. adapter.fill() should recieve some sort of table from the stored proc's output.
From what I can see here you are executing a stored procedure that only performs an INSERT command, The reason you are getting a NULL value back is because a non query command such as UPDATE or INSERT will generally return only the number of rows affected e.g. 1 and not the data of the table you inserted to.
You would need to perform a SELECT command after the insert to get any data back.
The problem is in your stored procedure... you have to add select statement to the stored procedure for your return result in DataSet
Because you use Insert Into in your stored procedure.
Access based on Tables property:
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dsDataSet);
var table1 = dsDataSet.Tables[0];
var table2 = dsDataSet.Tables[1];
Link : http://msdn.microsoft.com/fr-fr/library/system.data.dataset.tables.aspx
Related
I have this stored procedure that gets the product table with provided parameter
CREATE PROCEDURE DisplayProductParameter #id nvarchar(100)
AS
BEGIN
SET NOCOUNT ON;
SELECT P.product_id, P.product_name, P.product_price, T.[type_name], T.[type_fee], T.[type_id]
FROM Product P
INNER JOIN [Product Type] T ON P.[type_id] = T.[type_id]
WHERE P.product_id = #id
END;
GO
I call it with this function in C#
public SqlCommand InitSqlCommand(string query, CommandType commandType)
{
var Sqlcommand = new SqlCommand(query, con);
Sqlcommand.CommandType = commandType;
return Sqlcommand;
}
Then I store it in a DataTable
public DataTable GetData(SqlCommand command)
{
var dataTable = new DataTable();
var dataSet = new DataSet();
var dataAdapter = new SqlDataAdapter { SelectCommand = command };
dataAdapter.Fill(dataTable);
return dataTable;
}
Then this is how I get the DataTable
public DataTable DisplayProductParameter()
{
string getProductIdParam = "DisplayProductParameter";
var command = Connection.InitSqlCommand(getProductIdParam, CommandType.StoredProcedure);
command.Parameters.AddWithValue("#id", P.Id);
return Connection.GetData(command);
}
This is how I should autofill textboxes whenever I click on the combobox
private void cmbProductId_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
p.Id = cmbProductId.SelectedItem.ToString();
dtbProduct = po.DisplayProductParameter();
for (int i = 0; i < dtbProduct.Rows.Count; i++)
{
txtProductType.Text = dtbProduct.Rows[i]["type_name"].ToString();
txtPrice.Text = dtbProduct.Rows[i]["product_price"].ToString();
txtProductName.Text = dtbProduct.Rows[i]["product_name"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
But I get this error message at the start of the form
Procedure or function 'DisplayProductParameter' expects parameter
'#id', which was not supplied.
Logically your code seems correct.
In order to get more information on where and why this is happening, could you add a breakpoint on this line:
public DataTable DisplayProductParameter()
{
string getProductIdParam = "DisplayProductParameter";
var command = Connection.InitSqlCommand(getProductIdParam, CommandType.StoredProcedure);
-->command.Parameters.AddWithValue("#id", P.Id);
return Connection.GetData(command);
}
and run in debugging mode to see what the value of P.Id is. It could be passing a null or empty string value into the procedure.
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.
Here is my stored procedure:
CREATE Proc UpdateChecklist
(
#TemplateId As INT
) as
begin
select MF.CheckListDataId from TemplateModuleMap TM
inner join ModuleField MF
on TM.ModuleId = MF.ModuleId
where TM.TemplateId = #TemplateId and MF.CheckListDataId not in
(select cktm.CheckListDataId from ChecklistTemplateMap cktm
inner join ChecklistData ckd
on cktm.CheckListDataId = ckd.Id
where cktm.TemplateId = #TemplateId)
end
So I expect to have a returned list of CheckListDataId here. I'm trying to use Database.ExecuteSqlCommand() but not succeed yet. How can I return a list of CheckListDataId here? Do I need to modify my stored proc? I'm pretty new to sql.
Any suggestion? This is an ASP.NET MVC 5 project
Your Stored Procedure will return you a resultset and you can process that however you want in your C#.
I would call the procedure from inside my model class in this way:
DataTable loadLogFilterData = SQLHelper.ExecuteProc(STORED_PROCEDURE_NAME, new object[] {
//Parameters to Stored Proc If Any
});
Then I have a SQLHelper Class inside which I create the SQL Connection and have the delegate methods to call the stored procedures.
public static DataTable ExecuteProc(string procedureName, Object[] parameterList, string SQLConnectionString) // throws SystemException
{
DataTable outputDataTable;
using (SqlConnection sqlConnection = OpenSQLConnection(SQLConnectionString))
{
using (SqlCommand sqlCommand = new SqlCommand(procedureName, sqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
if (parameterList != null)
{
for (int i = 0; i < parameterList.Length; i = i + 2)
{
string parameterName = parameterList[i].ToString();
object parameterValue = parameterList[i + 1];
sqlCommand.Parameters.Add(new SqlParameter(parameterName, parameterValue));
}
}
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
DataSet outputDataSet = new DataSet();
try
{
sqlDataAdapter.Fill(outputDataSet, "resultset");
}
catch (SystemException systemException)
{
// The source table is invalid.
throw systemException; // to be handled as appropriate by calling function
}
outputDataTable = outputDataSet.Tables["resultset"];
}
}
return outputDataTable;
}
You have treat every output from a stored procedure as a resultset no matter what it contains. Then you need to manipulate that result set in your Model to populate the desired data structure and data type.
I'm trying to pass a data table to a stored procedure. The table has four columns, OldDifficulty, OldIndex, NewDifficulty, and NewIndex. It is passed to a stored procedure which is supposed to update all the rows in a Puzzles table changing rows with the old index and difficulty to their new index and difficulty. The Puzzles table does not change, and I can't figure out why. I'm not sure whether the problem is in the code or in the database query.
Here is the C# code that calls the stored procedure:
var Form = context.Request.Form;
DataTable table = new DataTable();
table.Columns.Add("OldDifficulty");
table.Columns.Add("OldIndex");
table.Columns.Add("NewDifficulty");
table.Columns.Add("NewIndex");
foreach (var key in Form.Keys)
{
var Old = key.ToString().Split('_');
var New = Form[key.ToString()].Split('_');
if (Old == New || New.Length == 1 || Old.Length == 1) continue;
table.Rows.Add(Old[0], int.Parse(Old[1]), New[0], int.Parse(New[1]));
}
using (var con = new SqlConnection(SqlHelper.ConnectionString))
{
con.Open();
using (var com = new SqlCommand("RearrangePuzzles", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(new SqlParameter("ChangedPuzzles", table)
{ SqlDbType = SqlDbType.Structured });
com.ExecuteNonQuery();
}
con.Close();
}
and here is the stored procedure:
ALTER PROCEDURE [dbo].[RearrangePuzzles]
#ChangedPuzzles ChangedPuzzlesTable READONLY
AS
UPDATE p
SET
NthPuzzle = cp.NewIndex,
Difficulty = cp.NewDifficulty
FROM
Puzzles p JOIN
#ChangedPuzzles cp ON cp.OldIndex = p.NthPuzzle AND cp.OldDifficulty = p.Difficulty
Do you have any idea why the table isn't updating? Is there something wrong with my SQL?
Everything looks ok, except:
com.Parameters.Add(new SqlParameter("ChangedPuzzles", table)
{ SqlDbType = SqlDbType.Structured });
I would change to:
com.Parameters.Add(new SqlParameter("#ChangedPuzzles", table)
{ SqlDbType = SqlDbType.Structured });
# sign - prefix in parameter name.
Use SQL Server Profiler to see whether this query actually is executed.
check the order of fields in the table type ChangedPuzzlesTable , it must be same as datatable any change in order may cause this problem
check error by adding a try catch
try
{
using (var con = new SqlConnection(SqlHelper.ConnectionString))
{
con.Open();
using (var com = new SqlCommand("RearrangePuzzles", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(new SqlParameter("ChangedPuzzles", table)
{ SqlDbType = SqlDbType.Structured });
com.ExecuteNonQuery();
}
con.Close();
}
}
catch (Exception ex)
{
// ex will show you the error
}
I am trying to get the data from database by using the below code.....
if there is no data in the table it will always goes to
this statement
I am using mysql.net connector for getting the data and i am doing winforms applications
using c#
public DataTable sales(DateTime startdate, DateTime enddate)
{
const string sql = #"SELECT memberAccTran_Source as Category, sum(memberAccTran_Value) as Value
FROM memberacctrans
WHERE memberAccTran_DateTime BETWEEN #startdate AND #enddate
GROUP BY memberAccTran_Source";
return sqlexecution(startdate, enddate, sql);
}
and the below code is for return sqlexceution...function..
private static DataTable sqlexecution(DateTime startdate, DateTime enddate, string sql)
{
var table = new DataTable();
using (var conn = new MySql.Data.MySqlClient.MySqlConnection(connectionstring))
{
conn.Open();
var cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
var ds = new DataSet();
var parameter = new MySql.Data.MySqlClient.MySqlParameter("#startdate", MySql.Data.MySqlClient.MySqlDbType.DateTime);
parameter.Direction = ParameterDirection.Input;
parameter.Value = startdate.ToString(dateformat);
cmd.Parameters.Add(parameter);
var parameter2 = new MySql.Data.MySqlClient.MySqlParameter("#enddate", MySql.Data.MySqlClient.MySqlDbType.DateTime);
parameter2.Direction = ParameterDirection.Input;
parameter2.Value = enddate.ToString(dateformat);
cmd.Parameters.Add(parameter2);
var da = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
da.Fill(ds);
try
{
table = ds.Tables[0];
}
catch
{
table = null;
}
}
return table;
}
even if there is no data the process flow will goes to this line
table = ds.Tables[0];
how can i reduce this .....
would any one pls help on this....
In your case if you are think that catch block will get excuted if there is no row available than you are wrong because Even if there is no data once select query is get exucuted without exception it Creates datatable with the columns but with no rows.
for this i think you can make use of ds.table[0].rows.count property which return 0 if there is no row in datatable.
if ( ds.Tables[0].Rows.Count > 0 )
table = ds.Tables[0];
else
table=null;
It returns an empty table. This is common behavior. If you want to have table null you should check for the row count :
If ( ds.Tables[0].Rows.Count >. 0 )
table = ds.Tables[0];
Else
table=0
I'm not really sure what you're asking here ... I assume you want it to skip the table = ds.tables[0] line if there is no data?
if thats the case a try/catch wont work as it wont throw an exception ... try something like this instead ...
if(ds.Tables.Count > 0 && ds.Tables[0].Rows.Count >0)
{
table = ds.Tables[0];
}
else
{
table = null;
}