I am working on website with C#.I have Store Registration Details in two table that is login and registration.Data is inserted in table. Now when i am on login page this email_id and pasword is selected from Database.So, for that i have created one Store procedure which is`
ALTER PROCEDURE [dbo].[P_M_Login]
#Email_id nvarchar(50),
#Password nvarchar(50),
#Tran_Type nvarchar(1)
AS
BEGIN
SET NOCOUNT ON;
IF #Tran_Type='I'
if not exists(select 1 from M_Login where Email_id=#Email_id)
BEGIN
INSERT INTO M_Login ( Email_id, Password)
VALUES(#Email_id,#Password);
end
ELSE
IF #Tran_Type='S'
BEGIN
Select Email_id,Password from M_Login;
END
END`
Now i want to use this Store Procedure in my three tier architecture how can i pass tran type so it will be perfect for me.
This is my DAL Class coding for calling store procedure.
public Int32 Login(BALRegistration objBEL)
{
int result;
try
{
SqlCommand cmd1 = new SqlCommand("P_M_Login", con);
cmd1.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("#Regisration_Id", objBEL.Registration_Id);
cmd1.Parameters.AddWithValue("#Email_id", objBEL.Email_id);
cmd1.Parameters.AddWithValue("#Password", objBEL.Password);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
result = cmd1.ExecuteNonQuery();
cmd1.Dispose();
if (result > 0)
{
return result;
}
else
{
return 0;
}
}
catch (Exception ex)
{
throw;
}
finally
{
if (con.State != ConnectionState.Closed)
{
con.Close();
}
}
}
}
}
Try this. Since you have parameter to be accepted in stored procedure, you just need to pass the parameter from the DAL
string type="s";
SqlCommand cmd1 = new SqlCommand("P_M_Login", con);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#Email_id", objBEL.Email_id);
cmd1.Parameters.AddWithValue("#Password", objBEL.Password);
cmd1.Parameters.AddWithValue("#Tran_Type ", type);
public void Insert(Order order)
{
SqlConnection con = DACHelper.GetConnection();
SqlCommand cmd = new SqlCommand(INSERT, con);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#Category_Id", order.Category.Id);
cmd.Parameters.AddWithValue("#Item_Id", order.Item.Id);
con.Open();
using (con)
{
SqlTransaction tran = con.BeginTransaction();
cmd.Transaction = tran;
try
{
order.Id= Convert.ToInt32(cmd.ExecuteScalar());
new OrderMailsDAC().Insert(order.Id, order.Mail , tran);
tran.Commit();
}
catch (Exception)
{
tran.Rollback();
throw;
}
}
}
then I inserted the order.Id in the following Insert function of OrderMails Class.
public void Insert(int orderId,OrderConfirmationMail mails,SqlTransaction tran)
{
SqlConnection con = tran.Connection;
SqlCommand cmd = new SqlCommand(INSERT, con);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Transaction = tran;
cmd.Parameters.AddWithValue("#Mail", mails.Mail);
cmd.Parameters.AddWithValue("#Order_Id", orderId);
cmd.ExecuteNonQuery();
}
The problem here is that the order.Id value when inserted into another Insert of OredrMail then it stores zero at that place.. The Column is autoincremented , ad.Id which we have stored in Order table ...
ExecuteScalar returns the first column of the first row returned. Typically we'd just have the procedure select a single value if we're expecting to receive a single value.
in your procedure declare a variable like
declare #id
then immediately after your insert,
set #id = scope_identity()
then when the procedure is done executing
select #id
You can actually condense all of that to
insert ....whatever
select scope_identity()
I just have a tendency to be more explicit in case any other operations in between replace the value of scope_identity().
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am having problem deleting user from table. I can insert the data from form to table but while deleting it only gives else statement result as "SOME ERRORS OCCURRED WHILE PROCESSING THE REQUEST". StaffID is auto increment. Please help.
Delete Button :
private void btnDeleteUser_Click(object sender, EventArgs e)
{
try
{
int result = uc.ManageUser(txtFullName.Text, txtAddress.Text, txtPhone.Text, txtEmail.Text, Convert.ToDateTime(dateTimePickerJoinedDate.Text), txtUserame.Text, txtPassword.Text, Convert.ToDateTime(dateTimePickerCreatedDate.Text), "D");
if (result == 1)
{
MessageBox.Show("User Deleted");
dgvUserDetails.DataSource = uc.SelectAllUsers();
//MakeFieldsBlank();
}
else
{
MessageBox.Show("SOME ERRORS OCCURRED WHILE PROCESSING THE REQUEST");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
}
}
ManageUser Class
public int ManageUser(String Name, String Address, String Phone, String Email, DateTime JoinedDate, String Username, String Password, DateTime CreatedDate, String Mode)
{
try
{
int result = 0;
SqlCommand cmd = new SqlCommand("sp_ManageUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#StaffID",DBNull.Value);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#Address", Address);
cmd.Parameters.AddWithValue("#Phone", Phone);
cmd.Parameters.AddWithValue("#Email", Email);
cmd.Parameters.AddWithValue("#JoinedDate", JoinedDate);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Password", Password);
cmd.Parameters.AddWithValue("#CreatedDate", CreatedDate);
//cmd.Parameters.AddWithValue("#IsActive", IsActive);
cmd.Parameters.AddWithValue("#Mode", Mode);
conn.Open();
result = cmd.ExecuteNonQuery();
conn.Close();
return result;
}
catch (Exception ex)
{
throw ex;
}
}
Procedure : sp_ManageUser
USE [db_ProjectStatusManager]
GO
/****** Object: StoredProcedure [dbo].[sp_ManageUser] Script Date: 12/05/2014 01:29:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[sp_ManageUser]
-- Add the parameters for the stored procedure here
#StaffID int,
#Name nvarchar(100),
#Address nvarchar(500),
#Phone nvarchar(100),
#Email nvarchar(100),
#JoinedDate date,
#Username nvarchar(50),
#Password nvarchar(max),
#CreatedDate date,
#Mode varchar(1)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT OFF;
-- Insert statements for procedure here
if(#Mode='I')
insert into tbl_Staff (Name,Address,Phone,Email,JoinedDate,Username,Password,CreatedDate) values(#Name,#Address,#Phone,#Email,#JoinedDate,#Username,#Password,#CreatedDate)
if(#Mode='U')
Update tbl_Staff set Name=#Name,Address=#Address,Phone=#Phone,Email=#Email,JoinedDate=#JoinedDate,Username=#Username,Password=#Password,CreatedDate=#CreatedDate where StaffID=#StaffID
if(#Mode='D')
Delete from tbl_Staff where StaffID=#StaffID
end
Load Users To TextBox
private void FrmUsers_Load(object sender, EventArgs e)
{
UserClass uc = new UserClass();
dgvUserDetails.DataSource = uc.SelectAllUsers();
dgvUserDetails.AllowUserToAddRows = false;
dgvUserDetails.AllowUserToOrderColumns = false;
panel1.Enabled = false;
}
UserClass. SelectAllUsers
public DataTable SelectAllUsers()
{
try
{
SqlCommand cmd = new SqlCommand("Select * from tbl_Staff", conn);
DataTable dt = new DataTable();
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dt.Load(dr);
conn.Close();
return dt;
}
catch (Exception ex)
{
throw ex;
}
}
You need to pass the value for the parameter #StaffID because the SP requires this parameter for the UPDATE and DELETE parts. It is only the INSERT part that doesn't require the #StaffID value
uc.ManageUser(txtStaffID.Text, txtFullName.Text, .......
....
public int ManageUser(string staffID, String Name, ......)
{
try
{
int result = 0;
SqlCommand cmd = new SqlCommand("sp_ManageUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#StaffID", Convert.ToInt32(staffID));
cmd.Parameters.AddWithValue("#Name", Name);
....
}
Of course this means that you need to save somewhere that value when you load your user data.
This could be a global variable or some textbox in readonly mode or hidden in your form or as a property of a User class. (This would a lot better. You could pass the whole instance of a User to your UserManager class instead of a lot of separated parameters)
Also pay attention to the datatype of the parameter #StaffID. The SP expects an integer not a string.
You are passing a NULL value in 'StaffID' column in command parameter but your store procedure has where condition with 'StaffID', first you need to Get the 'StaffID' and then pass the it.
you get the StaffID by simple query
Select StaffID from tbl_Staff where Name=#Name and Username = #Username ;
You can follow this code to get the Staffid
public int getstaffid()
{
int staffid = 0;
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
string query = " Select StaffID from tbl_Staff where Name=#Name and Username = #Username";
cmd.CommandText = query;
SqlParameter param = new SqlParameter("#Name", txtFullName.Text);
cmd.Parameters.Add(param);
SqlParameter param = new SqlParameter("#Username", txtUserame.Text);
cmd.Parameters.Add(param);
try
{
con.Open();
staffid= (Int32)cmd.ExecuteScalar();
return staffid;
}
catch (Exception ex)
{
throw;
}
}
And Now in ManagerUSer()
public int ManageUser(String Name, ......)
{
try
{
int Staffid = getstaffid();
int result = 0;
SqlCommand cmd = new SqlCommand("sp_ManageUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#StaffID",Staffid);
cmd.Parameters.AddWithValue("#Name", Name);
....
}
}
I have a method that sends two variables, an int and a delimited string, to an SQL Server proc.
Variable values (copied from debugger):
detailId: 5
fileNames: "recruiter.txt|cert.pdf"
The method:
public void InsertFiles(int detailId, string fileNames)
{
ConnectionStringSettings connString = ConfigurationManager.ConnectionStrings["PRADB"];
using (SqlConnection conn = new SqlConnection(connString.ToString()))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "dbo.InsertFiles";
cmd.Parameters.AddWithValue("#detailId", detailId);
cmd.Parameters.AddWithValue("#fileNames", fileNames);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
string exc = ex.ToString();
}
finally
{
conn.Close();
}
}
}
Here is the proc:
ALTER PROCEDURE [dbo].[InsertFiles]
#detailId int,
#fileNames varchar(max)
AS
BEGIN
SET NOCOUNT ON;
insert into [dbo].[PRA_Files] (detailId, fileNames)
values (#detailId, #fileNames)
END
The exception received when debugging:
{"Incorrect syntax near 'dbo'."}
Yet when I execute from the proc:
exec [dbo].[InsertFiles] 5, "recruiter.txt|cert.pdf"
It works fine. There error isn't code side as it is being caught in the catch block of the method above. I'm stumped.
You need to specify that the command is a stored procedure:
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "dbo.InsertFiles";
cmd.Parameters.AddWithValue("#detailId", detailId);
cmd.Parameters.AddWithValue("#fileNames", fileNames);
cmd.CommandType = CommandType.StoredProcedure;
I want to use a stored procedure in mySql and it must return identity_scope(). I try this but don't work:
CREATE DEFINER=`root`#`localhost` PROCEDURE `InsertVideo`(
OUT out_scope_id INT,
IN in_youtubeidvideo VARCHAR(15),
IN in_title VARCHAR(200),
IN in_rating DOUBLE,
IN in_viewcount INT
)
BEGIN
INSERT INTO Video
(
YoutubeIdVideo,
Title,
Rating,
ViewCount,
DataAdded,
ConvertedFlag
)
VALUES
(
in_youtubeidvideo,
in_title,
in_rating,
in_viewcount,
CURDATE(),
false
);
END
using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["AxWaveConnection"].ToString()))
{
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
MySqlCommand cmd = new MySqlCommand("InsertVideo", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("out_scope_id", scopeID);
cmd.Parameters.Add(new MySqlParameter("in_youtubeidvideo", VideoId));
cmd.Parameters.Add(new MySqlParameter("in_title", Title));
cmd.Parameters.Add(new MySqlParameter("in_viewcount", ViewCount));
cmd.Parameters.Add(new MySqlParameter("in_rating", Rating));
cmd.Parameters["out_scope_id"].Direction = ParameterDirection.Output;
try
{
cmd.ExecuteNonQuery();
scopeID = Convert.ToInt32(cmd.Parameters["out_scope_id"].Value);
}
catch (Exception)
{
scopeID = -1; //Duplicate Record
}
conn.Close();
}
You forgot to set the value of the parameter in your proc; the last line in your stored proc should read like this:
select out_scope_id = LAST_INSERT_ID();
BTW: SCOPE_IDENTITY() is a MS SQL Server function; not a MySQL function.
SELECT ##IDENTITY AS 'Identity';
GO