I am trying to get the value of output parameter of a stored procedure in c# function. when i execute the SP i am getting correct result in sql server but i can't get in c#. Can you please tell me how can i get the output value in c#. Below is the function i am trying to get the output value in C# DAC.
public DataSet GetOrderItemPictureByOrderId(int orderID, int PageIndex)
{
DataSet dtOrder = new DataSet();
/// Connect to database.
Database db = DatabaseFactory.CreateDatabase(CONNECTION_NAME);
using (DbCommand cmd = db.GetStoredProcCommand("uspGetOrderItemPicturePageWise"))
{
/// Set parameter values.
db.AddInParameter(cmd, "#OrderID", DbType.Int32, orderID);
db.AddInParameter(cmd, "#PageIndex", DbType.Int32, PageIndex);
db.AddInParameter(cmd, "#PageSize", DbType.Int32, 6);
db.AddOutParameter(cmd, "#RecordCount", DbType.Int32, 4);
try
{
dtOrder = db.ExecuteDataSet(cmd);
string outputValue = cmd.Parameters["#RecordCount"].Value.ToString(); // here i want to get the output value and want to return the value to main code
}
catch (Exception ex)
{
LogErrors.WriteError(ex);
}
}
return dtOrder;
}
}
Here i am calling the function :-
DataSet _ds = _orderPicDAC.GetOrderItemPictureByOrderId(OrderID, PageIndex);
My Store Procedure :--
CREATE PROCEDURE [dbo].[uspGetOrderItemPicturePageWise]
#OrderID int,
#PageIndex INT = 1
,#PageSize INT = 10
,#RecordCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY [PictureId] ASC
)AS RowNumber,
Orderid,
GenericFieldID,
ItemImage
INTO #Results
FROM [OrderPictures]
WHERE OrderID = #OrderID
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
END
Thanks for your help in advance.
If you want to get value of output parameter outside the method without changing the return type of the method, you may use out parameters in C#.
Change your method definition like below:
public DataSet GetOrderItemPictureByOrderId(int orderID, int PageIndex, out string outputValue)
{
//code here
outputValue = db.GetParameterValue(cmd, "#RecordCount");
//code here
}
and then call this method
string outvalue;
DataSet _ds = _orderPicDAC.GetOrderItemPictureByOrderId(OrderID, PageIndex,out outvalue;);
You will have the value in outvalue variable.
You can try with below
using (SqlConnection con = new SqlConnection(dc.Con))
{
using (SqlCommand cmd = new SqlCommand("SP_ADD", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#OrderID", DbType.Int32, orderID);
con.Open();
cmd.ExecuteNonQuery();
}
}
I am trying to import CSV file data to a SQL Server Database. I got more than 15000 rows and it keeps adding new rows everyday to the CSV file. All i need is insert newly added rows to the already existing database.
Problem i have right now, if i import the file its gonna insert everything including old 15000 rows. I was thinking to to insert csv data to a temporary table and filter out duplicate lines. but i dont know how to do it.
private void Save_Import_Data_SQL(DataTable importData)
{
using(SqlConnection conn = new SqlConnection(myconnstring))
{
conn.Open();
foreach(DataRow importRow in importData.Rows)
{
DateTime Start_Date_tt = ConvertStringToDate(importRow["Start date"].ToString());
Decimal Start_Time_tt = ConvertStringToDecimal(importRow["Start time"].ToString());
DateTime Finish_Date_tt = ConvertStringToDate(importRow["Finish date"].ToString());
Decimal Finish_Time_tt = ConvertStringToDecimal(importRow["Finish time"].ToString());
Decimal Pieces_tt = ConvertStringToDecimal(importRow["Pieces"].ToString());
Decimal cycle_tt = ConvertStringToDecimal(importRow["Average part cycle time"].ToString());
Decimal length_tt = ConvertStringToDecimal(importRow["Length_pa"].ToString());
SqlCommand cmd = new SqlCommand("INSERT INTO Silver_Robot(Program_S,Grpup_S,Start_Date_S,Start_Time_S,Pieces_S,Finish_Date_S,Finish_Time_S,Average_Part_Cycle_Time_S,Mode_S,Length_S) VALUES(#program,#group,#start_Date,#start_time,#pieces,#finish_date,#finish_time,#avarage_part,#mode_p,#length_p)", conn);
cmd.Parameters.AddWithValue("#program", importRow["Program"]);
cmd.Parameters.AddWithValue("#group", importRow["Group"]);
cmd.Parameters.AddWithValue("#start_Date", Start_Date_tt);
cmd.Parameters.AddWithValue("#start_time", Start_Time_tt);
cmd.Parameters.AddWithValue("#pieces", Pieces_tt);
cmd.Parameters.AddWithValue("#finish_date", Finish_Date_tt);
cmd.Parameters.AddWithValue("#finish_time", Finish_Time_tt);
cmd.Parameters.AddWithValue("#avarage_part", cycle_tt);
cmd.Parameters.AddWithValue("#mode_p", importRow["Mode"]);
cmd.Parameters.AddWithValue("#length_p", length_tt );
cmd.ExecuteNonQuery();
}
}
}
Any help would be appreciated
You can just use IF NOT EXIST in SQL: https://forums.asp.net/t/1738957.aspx?SqlCommand+with+IF+NOT+EXISTS+statement
SQL Server Insert if not exist
So probably if you just replace your SQL command:
SqlCommand cmd = new SqlCommand("INSERT INTO Silver_Robot(Program_S,Grpup_S,Start_Date_S,Start_Time_S,Pieces_S,Finish_Date_S,Finish_Time_S,Average_Part_Cycle_Time_S,Mode_S,Length_S) VALUES(#program,#group,#start_Date,#start_time,#pieces,#finish_date,#finish_time,#avarage_part,#mode_p,#length_p)", conn);
With something like this:
SqlCommand cmd = new SqlCommand("IF NOT EXISTS (SELECT * FROM Silver_Robot WHERE Program_S = #program AND Grpup_S = #group AND Start_Date_S = #start_Date AND Start_Time_S = #start_time AND Pieces_S = #pieces AND Finish_Date_S = #finish_date AND Finish_Time_S = #finish_time AND Average_Part_Cycle_Time_S = #avarage_part AND Mode_S = #mode_p AND Length_S = #length_p) BEGIN INSERT INTO Silver_Robot(Program_S,Grpup_S,Start_Date_S,Start_Time_S,Pieces_S,Finish_Date_S,Finish_Time_S,Average_Part_Cycle_Time_S,Mode_S,Length_S) VALUES(#program,#group,#start_Date,#start_time,#pieces,#finish_date,#finish_time,#avarage_part,#mode_p,#length_p) END", conn);
it should work.
But, as you can see in the first link it might be a good idea to create a stored procedure, because in that case you'll have a better performance.
This is how i fixed it, and so far everything working perfectly fine.
I created a procedure
USE [Electrical_ENG]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Silver_Robot_Insert]
#program varchar(50),
#group varchar(50),
#start_Date datetime,
#start_time varchar(50),
#pieces decimal,
#finish_date datetime,
#finish_time varchar(50),
#avarage_part decimal,
#mode_p varchar(50),
#length_p decimal,
#Total_Time_p decimal
AS
DECLARE #err_msg nvarchar(255);
IF NOT EXISTS(SELECT * FROM Silver_Robot WHERE Program_S=#program AND Grpup_S=#group AND Start_Date_S=#start_Date AND Start_Time_S=#start_time AND Pieces_S=#pieces AND Finish_Date_S=#finish_date AND Finish_Time_S=#finish_time AND Average_Part_Cycle_Time_S=#avarage_part AND Mode_S=#mode_p AND Length_S=#length_p AND Total_Time_S=#Total_Time_p)
BEGIN
INSERT INTO Silver_Robot(Program_S,Grpup_S,Start_Date_S,Start_Time_S,Pieces_S,Finish_Date_S,Finish_Time_S,Average_Part_Cycle_Time_S,Mode_S,Length_S,Total_Time_S)
VALUES(#program,#group,#start_Date,#start_time,#pieces,#finish_date,#finish_time,#avarage_part,#mode_p,#length_p,#Total_Time_p)
END
Insert:
public void Insert_Silver_Robot(String Program_S, String Grpup_S, DateTime Start_Date_S, String Start_Time_S, Decimal Pieces_S, DateTime Finish_Date_S, String Finish_Time_S, double Average_Part_Cycle_Time_S, String Mode_S, double Length_S, double Total_Time_S)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = con_str_S3;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "Silver_Robot_Insert";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#program", Program_S);
cmd.Parameters.AddWithValue("#group", Grpup_S);
cmd.Parameters.AddWithValue("#start_Date", Start_Date_S);
cmd.Parameters.AddWithValue("#start_time", Start_Time_S);
cmd.Parameters.AddWithValue("#pieces", Pieces_S);
cmd.Parameters.AddWithValue("#finish_date", Finish_Date_S);
cmd.Parameters.AddWithValue("#finish_time", Finish_Time_S);
cmd.Parameters.AddWithValue("#avarage_part", Average_Part_Cycle_Time_S);
cmd.Parameters.AddWithValue("#mode_p", Mode_S);
cmd.Parameters.AddWithValue("#length_p", Length_S);
cmd.Parameters.AddWithValue("#Total_Time_p", Total_Time_S);
//try
//{
conn.Open();
cmd.ExecuteNonQuery();
//}catch(Exception ex)
//{
// MessageBox.Show(ex.Message);
//}
//finally
//{
// if(con.State==ConnectionState.Open)
// {
conn.Close();
// }
// }
}
}
In upload click event:
foreach (DataRow importRow in importData.Rows)
{
DateTime Start_Date_tt = ConvertStringToDate(importRow["Start date"].ToString());
DateTime Finish_Date_tt = ConvertStringToDate(importRow["Finish date"].ToString());
Decimal Pieces_tt = ConvertStringToDecimal(importRow["Pieces"].ToString());
double cycle_tt = ConvertStringToDouble(importRow["Average part cycle time"].ToString());
double length_tt = ConvertStringToDouble(importRow["Length_pa"].ToString());
double total_time_tt = cycle_tt * length_tt;
string program_tt = importRow["Program"].ToString();
string group_tt = importRow["Group"].ToString();
string start_time_tt = importRow["Start time"].ToString();
string finish_time_tt = importRow["Finish time"].ToString();
string mode_tt = importRow["Mode"].ToString();
dbactions.Insert_Silver_Robot(program_tt,group_tt,Start_Date_tt,start_time_tt,Pieces_tt,Finish_Date_tt,finish_time_tt,cycle_tt, mode_tt,length_tt,total_time_tt);
}
Again using a bulkinsert would be the best way to do this but i do not have permission to use it in my server. And thanks for all the help.
hi all i am having a problem with returning a value of a sql server scalar valued function in a specific datagridview column, the code is below:-
1- sql function:-
CREATE FUNCTION [dbo].[ToLocationID](#ID int)
RETURNS varchar(50)
AS
BEGIN
-- Declare the return variable here
DECLARE #LocationName varchar(50)
-- Add the T-SQL statements to compute the return value here
SELECT #LocationName=dbo.Location.LocationName FROM Location WHERE LocationID=#ID
-- Return the result of the function
RETURN #LocationName
END
2-C# Method to execute the function:-
public static string MyMethod(int ID) {
string SqlConnStr = globals.ServerConnStr;
SqlConnection SqlConn = new SqlConnection(SqlConnStr);
try
{
SqlConn.Open();
SqlCommand cmd = new SqlCommand("SELECT dbo.ToLocationID(#ID)", SqlConn);
cmd.Parameters.Add(new SqlParameter("#ID", ID));
return cmd.ExecuteScalar().ToString();
}
finally
{
SqlConn.Close();
}
}
and here is the gridview code:-
//GetAllTransfers is a method that executes a stored procedure to return most of the //columns like the column["Date"] below
dataGridViewList.DataSource = Data.GetAllTransfers();
dataGridViewList.Columns["Date"].HeaderText = "Date";
dataGridViewList.Columns.Add("ToLocationID", "To Location");
dataGridViewList.Columns["ToLocationID"].DisplayIndex = 5;
dataGridViewList.Columns["ToLocationID"].Tag = Data.MyMethod(1);
I just want to fill the column "ToLocationID" with the result of the scalar function from the method "MyMethod", what is wrong with this code?
I have written a stored procedure for simple user Login function.
USE [project]
GO
/****** Object: StoredProcedure [dbo].[authenticateLogin] Script Date: 10/18/2013 9:24:57 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[authenticateLogin] #userName varchar, #password varchar
AS
BEGIN
Declare #userRole int;
Declare #uPassword varchar;
Declare #uRole int;
SET #uPassword = (SELECT uPassword FROM [user] WHERE uName=#userName);
IF(#uPassword = #password)
SET #userRole = (SELECT uRole FROM [user] WHERE uName=#userName);
ELSE
SET #userRole = 0;
--RETURN #userRole
SELECT #userRole
END
And I am calling this from my program like this:
internal int Authenticate(string userName, string password)
{
int userRole = 0;
Shared shrObj=new Shared();
string encPassword = shrObj.EncryptToString(password);
SqlConnection sqlCon = Shared.GetSqlCon();
var sqlCom = new SqlCommand("authenticateLogin", sqlCon);
sqlCom.CommandType = CommandType.StoredProcedure;
sqlCom.Parameters.AddWithValue("#userName", userName);
sqlCom.Parameters.AddWithValue("#password", encPassword);
try
{
userRole = Shared.ExecuteNonQueryOnProcedure(sqlCon, sqlCom);
if (userRole > 0) return userRole;
}
catch (SqlException sqlEx)
{
//catch
}
finally
{
Shared.COC(sqlCon);
}
return userRole;
}
In Shared.cs
public static int ExecuteNonQueryOnProcedure(SqlConnection sqlCon, SqlCommand sqlCom) {
int rowCount = 0;
SqlParameter returnParameter = sqlCom.Parameters.Add("userRole", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
try
{
sqlCon.Open();
//rowCount = sqlCom.ExecuteNonQuery();
var inu = sqlCom.ExecuteScalar().ToString();
}
catch (Exception ex)
{
//catch
return rowCount;
}
return (int)returnParameter.Value;
}
But the issue is it always return me 0 even where provided arguments are matched. please help me where am i doing wrong.
You shouldn't pass EXEC procedure with SqlCommand. Use CommandType.StoredProcedure
var sqlCom = new SqlCommand("authenticateLogin",sqlCon);
sqlComm.CommandType = CommandType.StoredProcedure; //here
sqlCom.Parameters.AddWithValue("#userName", userName);
sqlCom.Parameters.AddWithValue("#password", encPassword);
try
{
userRole = (short)sqlComm.ExecuteScalar();
if (userRole > 0) return userRole;
}
To get Return Value you can add a parameter like:
SqlParameter returnParameter = sqlCom.Parameters.Add("userRole", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
sqlCom.ExecuteScalar();
int returnValue = (int) returnParameter.Value;
In your SQL you should have
SELECT #userRole
instead of
RETURN #userRole
ExecuteScalar() will execute the command and return value of the first column in the first row that the SQL command produces, not the return value.
You don't return a value from an SP like that, in fact the return value is not much use.
If you want to use an SP for authentication like that then something like the following would work:
CREATE PROCEDURE [dbo].[authenticateLogin] #userName varchar, #password varchar
AS
BEGIN
SELECT uRole FROM [User]
WHERE uName=#userName AND uPassword = #password
This will return the uRole field for all users with a matching username and password which will hopefully be either 1 or 0 rows.
ok Guys, got it working it was a stupid mistake which me or neither anyone else realized.
I was not specifying the characters values in varchar(?) hence it was only taking first character of every variable and hence the if-Else block was failing. fixed that and everything is fine now.
Thanks everyone for helping out. :)
How can I use a stored procedure (with parameters - has a return value of type int) from code behind?
My stored procedure looks like this :
ALTER Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
#Co_ID int
AS
-----------------
Declare #Sum bigint
-----------------
BEGIN
SELECT
#Sum = SUM(TotalPay)
FROM Noskheh
WHERE
(Co_ID = #Co_ID)
RETURN #Sum
END
I want to use #Sum in code behind ...
Would you please show me a way for doing that ?
Thanks in advance
best regards
You need to set up a SqlConnection and a SqlCommand. If you have your code with the RETURN #Sum statement in the end, you need to do this (define a parameter of type RETURN_VALUE):
using(SqlConnection _conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("#CO_ID", SqlDbType.Int));
_cmd.Parameters["#CO_ID"].Value = 5; // whatever value you want
_cmd.Parameters.Add(new SqlParameter("#RETURN_VALUE", SqlDbType.BigInt));
_cmd.Parameters["#RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;
_conn.Open();
_cmd.ExecuteNonQuery();
Int64 result = Int64.Parse(_cmd.Parameters["#RETURN_VALUE"].Value);
_conn.Close();
}
It would be a lot easier if you would replace that RETURN statement with a simple SELECT:
SELECT #Sum
In that case, you can use the simplified version I had before - using .ExecuteScalar() to retrieve the single value of the single row being returned from the stored proc:
using(SqlConnection _conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("#CO_ID", SqlDbType.Int));
_cmd.Parameters["#CO_ID"].Value = 5; // whatever value you want
_conn.Open();
object result = _cmd.ExecuteScalar();
_conn.Close();
Int64 sum = Int64.Parse(result);
}
That should call your stored proc, read the single value you're returning, and converting it into an int variable called sum.
There is no shortage of tutorials on this subject.
You can add an SqlParameter #Sum with Direction set to ReturnValue
Example:
SqlCommand cmd = new SqlCommand():
cmd.Connection = // place your SqlConnection object;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "StoreProcedureName";
cmd.Parameters.Add("#Sum", SqlDbType.BigInt).Direction = ParameterDirection.ReturnValue