Insert Select with Same Store Procedure - c#

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);

Related

Procedure has no parameters and arguments were supplied exception while my stored procedure accepts a parameter

below is the stored proc:
ALTER PROCEDURE Retrieve_Data
#noOfRecords INTEGER
AS
BEGIN TRY
SET NOCOUNT ON;
SELECT TOP(#noOfRecords) studentId
FROM Student;
END TRY
BEGIN CATCH
RETURN -101
END CATCH
RETURN 0
Below is the C# code:
DataSet ds = null;
try
{
using (SqlConnection conn = new SqlConnection(ConfigurationSettings.ConectionString))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = new SqlCommand(storeProcName, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter param= new SqlParameter("#noOfRecords", SqlDbType.Int);
param.Value=10;
da.SelectCommand.Parameters.Add(param);
ds = new DataSet();
da.Fill(ds, "result");
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
return ds;
}
}
}
While executing the code I am getting a sql exception:
Procedure Retrieve_Data has no parameters and arguments were supplied
The syntax of your stored procedure is incorrect. You need to provide the input parameters inside brackets
ALTER PROCEDURE [dbo].[Retrieve_Data]
(
#noOfRecords INT
)
AS
BEGIN
Also you can try to clear your parameters inside the code:
if (conn.State == ConnectionState.Open)
{
da.SelectCommand.Parameters.Clear();;
conn.Close();
}
Change your stored procedure and wrap with BEGIN ... END
ALTER PROCEDURE [dbo].[Retrieve_Data]
#noOfRecords INT
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
SELECT TOP(#noOfRecords) studentId
FROM Student;
END TRY
BEGIN CATCH
RETURN -101
END CATCH
RETURN 0;
END
Second thing about ordering table Student using ORDER BY ...

How to drop a table

I am using following C# method to execute SQL queries:
public bool ExecuteQuery(String pQuery)
{
SqlConnection con = new SqlConnection("MyConnectionString");
con.Open();
SqlTransaction trans = con.BeginTransaction(IsolationLevel.ReadCommitted);
try
{
SqlCommand cmd = new SqlCommand(pQuery, con, trans);
cmd.ExecuteNonQuery();
trans.Commit();
con.Close();
trans.Dispose();
return true;
}
catch (Exception exp)
{
trans.Rollback();
con.Close();
MessageBox.Show(exp.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}
When I pass this statement:
ExecuteQuery("DROP TABLE MyTable");
then the method returns true, which means it worked fine, but when I check SQL Server, myTable was not dropped. If I run the same statement in SQL Server Management Studio, MyTable is dropped...
Where am I wrong?
Before answering your question, some comments:
Avoid coding such operations using query text, this is a high chance you can get problems with security. Better create stored procedure that executes table drop:
create procedure sp_DropTable
#tablename varchar(200)
as
BEGIN
DECLARE #SQL VARCHAR(MAX);
SET #SQL = 'IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N''' + #tableName + ''') AND type = (N''U'')) DROP TABLE [' + #tableName + ']'
EXEC (#SQL);
END
GO
Then pass the stored procedure's name as parameter to your function. Now back to your error.
Table drop is not a transaction, but you try to execute it in transactional schema. This makes it fail. Try:
public bool ExecuteQuery(String pQuery)
{
SqlConnection con = new SqlConnection("MyConnectionString");
con.Open();
try
{
SqlCommand cmd = new SqlCommand(pQuery, con);
// if you pass just query text
cmd.CommandType = CommandType.Text;
// if you pass stored procedure name
// cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
con.Close();
return true;
}
catch (Exception exp)
{
con.Close();
MessageBox.Show(exp.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}

Can't delete User from table through windows form [closed]

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);
....
}
}

executenonquery not working in for loop

In database:
Alter Procedure Update_MaterialTransactionsto2ForWithdrawal
#materialName varchar(50),
#staffNumber varchar(10),
#description varchar(50),
#transactionID int
As
Begin
Update Table_MaterialTransactions
set Status=2
where StaffNumber = #staffNumber
and CrossSection = #description
and SubSubCategory = #materialName
and Status = 1
and TransactionID = #transactionID
End
In data access layer:
public static void UpdateMaterial(string staffNumber,string materialName,string description,int transaction)
{
SqlConnection connection = new SqlConnection(ConnectDatabase.ReturnConnectionString());
//I am passing connection string as the parameter
try
{
connection.Open();
SqlCommand cmd = new SqlCommand("Update_MaterialTransactionsto2ForWithdrawal", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.Add("#materialName", SqlDbType.Varchar, 50).Value = materialName;
cmd.Parameters.Add("#staffNumber", SqlDbType.Varchar, 50).Value = staffNumber;
cmd.Parameters.Add("#description", SqlDbType.Varchar, 50).Value = description;
cmd.Parameters.Add("#transactionID", SqlDbTypeInt).Value = transactionID;
int i = cmd.ExecuteNonQuery();
connection.Close();
}
catch(Exception ex)
{
connection.Close();
}
On the client side:
void btnSubmit_Click(Object sender,EventArgs e)
{
int j=0,k=0;
for(int i=0;i<transactions.Count;i++)
{
string id = "ctl00$ContentPlaceHolder1$" + i.ToString();
CheckBox chk=(CheckBox)Page.FindControl(id);
if(chk.Checked == true)
{
Objects.UpdateMaterial(staffNumbers[i].ToString(), materials[i].ToString(), descriptions[i].ToString(), Convert.ToInt32(transactions[i]));
j++;
}
else
{
Objects.DeleteTheSelectedRowOfMaterialTransaction(staffNumbers[i].ToString(), materials[i].ToString(), descriptions[i].ToString(), Convert.ToInt32(transactions[i]));
k++;
}
}
I have check boxes in the table and when the user checks the check boxes and clicks submit, the boxes which are checked will update the database.
But the cmd.ExecuteNonQuery() is not executing and it is returning 0 rows. It is not throwing any error. But if I do this manually in the database, the stored procedure is working fine.
Kindly tell me where I am going wrong.
try adding last line in procedure
Return ##Rowcount

Error in mysql stored procedure with c#

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

Categories