I'm trying to add a new user to table using a SQL Server stored procedure, but it's not being added, and it does not shows any errors, either.
C# code:
public void ADD_USER(string firstname, string lastname, string username, string password, string birthdate, string shiftstart, string shiftend, string ssn, string address, int salary, byte[] id_image, byte[] avatar)
{
DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
DAL.Open();
SqlParameter[] param = new SqlParameter[12];
param[0] = new SqlParameter("#USERNAME", SqlDbType.VarChar,100);
param[0].Value = username;
param[1] = new SqlParameter("#PASSWORD", SqlDbType.VarChar, 100);
param[1].Value = password;
param[2] = new SqlParameter("#FIRSTNAME", SqlDbType.VarChar, 100);
param[2].Value = firstname;
param[3] = new SqlParameter("#LASTNAME", SqlDbType.VarChar, 100);
param[3].Value = lastname ;
param[4] = new SqlParameter("#BIRTHDATE", SqlDbType.Date);
param[4].Value = birthdate;
param[5] = new SqlParameter("#ADDRESS", SqlDbType.VarChar, 100);
param[5].Value = address;
param[6] = new SqlParameter("#SSN", SqlDbType.Int);
param[6].Value = ssn;
param[7] = new SqlParameter("#SHIFTSTART", SqlDbType.Time);
param[7].Value = shiftstart;
param[8] = new SqlParameter("#SHIFTEND", SqlDbType.Time);
param[8].Value = shiftend;
param[9] = new SqlParameter("#SALARY", SqlDbType.Int);
param[9].Value = salary;
param[10] = new SqlParameter("#ID_IMAGE", SqlDbType.Image);
param[10].Value = id_image;
param[11] = new SqlParameter("#AVATAR", SqlDbType.Image);
param[11].Value = avatar;
try
{
DAL.executeCommand("ADD_USER", param);
}
catch (SqlException ex)
{
Console.Write(ex.Message);
}
DAL.close();
}
Stored procedure code:
CREATE PROC ADD_USER
#USERNAME VARCHAR(100),
#PASSWORD VARCHAR(100),
#FIRSTNAME VARCHAR(100),
#LASTNAME VARCHAR(100),
#BIRTHDATE VARCHAR(100),
#ADDRESS VARCHAR(100),
#SSN INT,
#ID_IMAGE IMAGE,
#AVATAR IMAGE,
#SHIFTSTART VARCHAR(100),
#SHIFTEND VARCHAR(100),
#SALARY INT
AS
INSERT INTO [CAFE].[dbo].[users] ([username], [password],
[firstname], [lastname], [SSN],
[id_image], [avatar],
[start_working], [shift_start], [shift_end],
[salary], [birth_date], [address])
VALUES (#USERNAME, #PASSWORD,
#FIRSTNAME, #LASTNAME, #SSN,
#ID_IMAGE, #AVATAR,
CONVERT(DATE, GETDATE()), #SHIFTSTART, #SHIFTEND,
#SALARY, #BIRTHDATE, #ADDRESS)
The stored procedure works fine on SQL Server itself, but doesn't add any records from C# code
I tried to trace this issue but I didn't get a result.
I'm using SQL Server 2008 R2 And Visual Studio 2015
Related
I ran into a problem for which I couldn't find a solution in existing similarly asked questions. The problem is that I have the following stored procedure:
ALTER PROCEDURE SP_EditCustomer #ID int, #Name NVarchar(100), #Email Nvarchar(200), #Contact bigint,
#Address NVarchar(350), #About NVarChar(350), #Image image = null
AS
if(#Image is null)
Begin
UPDATE clientTable
SET ClientName = #Name, Contact= #Contact, Address = #Address, About = #About, Email = #Email
WHERE ClientID = #ID;
End
Else
Begin
UPDATE clientTable
SET ClientName = #Name, Contact= #Contact, Address = #Address, About = #About, Email = #Email,
Photo = #Image
WHERE ClientID = #ID;
End
I have set the #image parameter to be null as default but whenever I connect to SQL Server with the following code in C# winforms:
// Inserting image into DB
byte[] img = null;
if (imgLoc != null && imgLoc != "")
{
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
}
else
{
img = null;
}
//Connecting to Database
cmd = conString.CreateCommand();
cmd.CommandText = "Exec SP_EditCustomer #ID, #Name, #Email, #Contact, #Address, #About, #Image";
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(txtEditByID.Text);
cmd.Parameters.Add("#Name", SqlDbType.NVarChar, 100).Value = txtFullName.Text.ToString();
cmd.Parameters.Add("#Email", SqlDbType.NVarChar, 200).Value = txtEmail.Text.ToString();
cmd.Parameters.Add("#Contact", SqlDbType.BigInt).Value = txtContact.Text;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar, 350).Value = txtAddress.Text.ToString();
cmd.Parameters.Add("#About", SqlDbType.NVarChar, 350).Value = txtAbout.Text.ToString();
cmd.Parameters.Add("#Image", SqlDbType.Image).Value = img;
conString.Open();
cmd.ExecuteNonQuery();
conString.Close();
I get this error:
The parameterized query '(#ID int,#Name nvarchar(100),#Email nvarchar(200),#Contact bigin' expects the parameter '#Image', which was not supplied.
Although if no new image is selected then the existing image shouldn't change (and for this purpose I have passed null but still I get the error above).
Thanks to #DaleK for suggesting the DBNull.Value.
I have solved it with his suggestion by adding the following lines:
if(img!=null)
cmd.Parameters.Add("#Image", SqlDbType.Image).Value = img;
else
cmd.Parameters.Add("#Image", SqlDbType.Image).Value = DBNull.Value;
I want to pass and add data to the web service through a desktop program by stored procedure in SQL Server.
Stored procedure
ALTER PROCEDURE [dbo].[insert_user]
(#code nvarchar(50),
#codeuser nvarchar(50),
#pictureuser image,
#nameshop nvarchar(50),
#country nvarchar(50),
#addressuser nvarchar(50),
#telephone nvarchar(20),
#passworact nvarchar(20),
#dateregist date,
#active bit)
AS
INSERT INTO user_tb (code, codeuser, pictureuser, nameshop,
country, addressuser, telephone, passworact, dateregist, active)
VALUES (#code, #codeuser, #pictureuser, #nameshop,
#country, #addressuser, #telephone, #passworact, #dateregist, #active)
Web service add
[WebMethod]
public int Insertregester(string code, string codeuser, byte pictureuser, string nameshop, string country, string addressuser, string telephone, string passworact, DateTime dateregist, Boolean active)
{
int retRecord = 0;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("insert_user", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#code", SqlDbType.NVarChar).Value = code;
cmd.Parameters.Add("#codeuser", SqlDbType.NVarChar).Value = codeuser;
cmd.Parameters.Add("#pictureuser", SqlDbType.Image).Value = pictureuser;
cmd.Parameters.Add("#nameshop", SqlDbType.NVarChar).Value = nameshop;
cmd.Parameters.Add("#country", SqlDbType.NVarChar).Value = country;
cmd.Parameters.Add("#addressuser", SqlDbType.NVarChar).Value = addressuser;
cmd.Parameters.Add("#telephone", SqlDbType.NVarChar).Value = telephone;
cmd.Parameters.Add("#passworact", SqlDbType.NVarChar).Value = passworact;
cmd.Parameters.Add("#dateregist", SqlDbType.Date).Value = dateregist.ToShortDateString();
cmd.Parameters.Add("#active", SqlDbType.Bit).Value = active;
if (con.State != ConnectionState.Open)
{
con.Open();
}
retRecord = cmd.ExecuteNonQuery();
}
}
return retRecord
}
Call service code in windows app
Servicea.WebServiceSoapClient _service = new WindowsForm_webservice.Servicea.WebServiceSoapClient();
This is the first time I have used the service.
My attempt:
ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);
_service.Insertregester(("22"), ("4578"), (photo_aray), (TEXT_NAME.Text), (TEXT_ADDRESS.Text), (TEXT_ADDRESS.Text), (TEXT_TEL.Text), (TEXT_PASSWO.Text),(DATE_PICK.Value.ToShortDateString),(true));
I get this error:
I am using a GridView, and I followed instructions here: http://www.aspsnippets.com/Articles/GridView-CRUD-Select-Insert-Edit-Update-Delete-using-Single-Stored-Procedure-in-ASPNet.aspx
Now I am getting the error: Procedure or function 'spRegistrantsGridView' expects parameter '#RegistrantId', which was not supplied
This is my StoredProcedure:
ALTER PROCEDURE [dbo].[spRegistrantsGridView]
#Action nvarchar(10),
#RegistrantId int,
#FirstName nvarchar(20),
#LastName nvarchar(25),
#AddressLine1 nvarchar(50),
#AddressLine2 nvarchar(50),
#City nvarchar(30),
#State nvarchar(2),
#Zip nvarchar(10),
#Country nvarchar(20),
#Phone nvarchar(15),
#PhoneExt nvarchar(4),
#Email nvarchar(50),
#MemberId bigint,
#Comments nvarchar(300)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
--SELECT
IF #Action = 'SELECT'
BEGIN
SELECT RegistrantId,
FirstName,
LastName,
AddressLine1,
AddressLine2,
City,
State,
Zip,
Country,
Phone,
PhoneExt,
Email,
Comments
FROM Registrant
END
--INSERT
IF #Action = 'INSERT'
BEGIN
INSERT INTO Registrant(
FirstName,
LastName,
AddressLine1,
AddressLine2,
City,
State,
Zip,
Country,
Phone,
PhoneExt,
Email,
MemberId,
Comments)
VALUES (
#FirstName,
#LastName,
#AddressLine1,
#AddressLine2,
#City,
#State,
#Zip,
#Country,
#Phone,
#PhoneExt,
#Email,
#MemberId,
#Comments)
END
--UPDATE
IF #Action = 'UPDATE'
BEGIN
UPDATE Registrant SET
FirstName = #FirstName,
LastName = #LastName,
AddressLine1 = #AddressLine1,
AddressLine2 = #AddressLine2,
City = #City,
State = #State,
Zip = #Zip,
Country = #Country,
Phone = #Phone,
PhoneExt = #PhoneExt,
Email = #Email,
MemberId = #MemberId,
Comments = #Comments
WHERE RegistrantId = #RegistrantId
END
--DELETE
IF #Action = 'DELETE'
BEGIN
DELETE FROM Registrant
WHERE RegistrantId = #RegistrantId
END
END
And the part of my C# where it throws the error (specifically at sda.Fill(dt);):
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("spRegistrantsGridView"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "SELECT");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
The parameter #RegistrantId wasn't added when calling the stored procedure.
Add the parameter to your code like so:
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("spRegistrantsGridView"))
{
cmd.CommandType = CommandType.StoredProcedure;
// missing parameter
cmd.Parameters.AddWithValue("#RegistrantId", [insert id]);
cmd.Parameters.AddWithValue("#Action", "SELECT");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
EDIT
Now your SP is in your question the issue is you have multiple parameters specified but you're only adding one in your c# code. Either remove the params from your SP or make them optional by adding = null
e.g.
ALTER PROCEDURE [dbo].[spRegistrantsGridView]
#Action nvarchar(10),
#RegistrantId int = null,
#FirstName nvarchar(20) = null,
...
I have written a simple stored procedure with some output parameters, but when I execute it from my C# code, I get an error
Expects Parameters
It is expecting me provide values for the OUTPUT parameters ...
Please help me figure out the error ...
My stored procedure:
ALTER PROCEDURE [dbo].[Check_EntryTrade_value]
#Account_ID bigint,
#Date datetime2(7),
#tradeby varchar(20),
#Symbol varchar(20),
#B_S varchar(20),
#RateE float ,
#Usd_Marg bigint OUTPUT,
#Amount bigint OUTPUT,
#Rate float OUTPUT,
#Entry_Order_id bigint OUTPUT
AS
BEGIN
SELECT
#Rate = [Rate],
#Entry_Order_id = [EntryOrder_ID],
#Amount = [Amount],
#Usd_Marg = [Usd_Mrg]
FROM
[dbo].[entrytable]
WHERE
[B_S] = #B_S
AND [Rate] = #RateE
AND [Account_ID] = #Account_ID
AND [Symbol] = #Symbol;
IF (#Rate IS NOT NULL)
INSERT INTO neworder (Account_ID, Symbol, B_S, Rate, Amount, Date, Usd_Marg, tradeby)
VALUES(#Account_ID, #Symbol, #B_S, #Rate, #Amount, #Date, #Usd_Marg, #tradeby);
DELETE FROM entrytable WHERE EntryOrder_ID = #Entry_Order_id;
END
And this is my C# Code:
SqlConnection conn = new SqlConnection(Properties.Settings.Default.MyCon);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
//SQL INJECTION '"+ +"'
cmd.CommandText = "Check_EntryTrade_value";
SqlParameter pID1 = new SqlParameter("#Account_ID", SqlDbType.BigInt, 10);
pID1.Value = 1;
SqlParameter pID2 = new SqlParameter("#Symbol", SqlDbType.VarChar, 20);
pID2.Value = "EUR/USD";
SqlParameter pID3 = new SqlParameter("#B_S", SqlDbType.VarChar, 20);
pID3.Value = "Buy";
SqlParameter pID4 = new SqlParameter("#RateE", SqlDbType.Float, 10);
pID4.Value = 1.24763;
//SqlParameter pID6 = new SqlParameter("#Amount", SqlDbType.BigInt, 10);
//pID6.Value = 1;
SqlParameter pID5 = new SqlParameter("#Date", SqlDbType.DateTime2, 7);
pID5.Value = DateTime.Now.ToShortDateString();
SqlParameter pID6 = new SqlParameter("#tradeby", SqlDbType.VarChar, 20);
pID6.Value = "User";
cmd.Parameters.Add(pID1);
cmd.Parameters.Add(pID2);
cmd.Parameters.Add(pID3);
cmd.Parameters.Add(pID4);
cmd.Parameters.Add(pID5);
cmd.Parameters.Add(pID6);
cmd.ExecuteNonQuery();
Running my C# code returns this error:
Procedure or Function 'Check_EntryTrade_value' expects parameter '#Usd_Marg', which was not supplied.
I Found it :) .. Thanks Every One for Help .. i love StackOverFlow :P
Here is what i did :
//STEP-1 CONNECTION
SqlConnection conn = new SqlConnection(Properties.Settings.Default.MyCon);
//STEP-2 COmmand
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
//SQL INJECTION '"+ +"'
cmd.CommandText = "Check_EntryTrade_value";
SqlParameter pID1 = new SqlParameter("#Account_ID", SqlDbType.BigInt, 10);
pID1.Value = 1;
SqlParameter pID2 = new SqlParameter("#Symbol", SqlDbType.VarChar, 20);
pID2.Value = "EUR/USD";
SqlParameter pID3 = new SqlParameter("#B_S", SqlDbType.VarChar, 20);
pID3.Value = "Buy";
SqlParameter pID4 = new SqlParameter("#RateE", SqlDbType.Float, 10);
pID4.Value = 1.24763;
//SqlParameter pID6 = new SqlParameter("#Amount", SqlDbType.BigInt, 10);
//pID6.Value = 1;
SqlParameter pID5 = new SqlParameter("#Date", SqlDbType.DateTime2, 7);
pID5.Value = DateTime.Now.ToShortDateString();
SqlParameter pID6 = new SqlParameter("#tradeby", SqlDbType.VarChar, 20);
pID6.Value = "User";
SqlParameter pID7 = new SqlParameter("#Usd_Marg", SqlDbType.BigInt, 10);
pID7.Direction = ParameterDirection.Output;
// pID6.Value = "User";
SqlParameter pID8 = new SqlParameter("#Amount", SqlDbType.BigInt, 20);
pID8.Direction = ParameterDirection.Output;
// pID6.Value = "User";
SqlParameter pID9 = new SqlParameter("#Rate", SqlDbType.BigInt, 20);
pID9.Direction = ParameterDirection.Output;
// pID6.Value = "User";
SqlParameter pID10 = new SqlParameter("#Entry_Order_id", SqlDbType.BigInt, 20);
pID10.Direction = ParameterDirection.Output;
// pID6.Value = "User";
cmd.Parameters.Add(pID1);
cmd.Parameters.Add(pID2);
cmd.Parameters.Add(pID3);
cmd.Parameters.Add(pID4);
cmd.Parameters.Add(pID5);
cmd.Parameters.Add(pID6);
cmd.Parameters.Add(pID7);
cmd.Parameters.Add(pID8);
cmd.Parameters.Add(pID9);
cmd.Parameters.Add(pID10);
Try to remove
#Usd_Marg bigint OUTPUT,
#Amount bigint OUTPUT,
#Rate float OUTPUT,
#Entry_Order_id bigint OUTPUT
from stored procedure definition .
Modify your query :
SELECT [Rate], [EntryOrder_ID],[Amount],[Usd_Mrg]
FROM [dbo].[entrytable]
WHERE [B_S] = #B_S AND [Rate] = #RateE AND [Account_ID] = #Account_ID AND [Symbol] = #Symbol;
On the C# side you will receive a data set so you need to change last line of c# code :
cmd.ExecuteScalar();
I want to know what (if any) is wrong with the below stored procedure for updating address:
I have also given my database image to get a clear idea....
ALTER PROCEDURE [dbo].[usp_UpdateAddress]
(#OriginalEmail nvarchar(50), #FirstName varchar(50), #LastName varchar(50),
#Country_ID int, #AddressLine1 varchar(50), #AddressLine2 varchar(50),
#AddressLine3 varchar(50), #Telephone varchar(50), #Email nvarchar(50),
#City varchar(50), #State_ID int, #PostalCode varchar(50), #Mobile varchar(50))
AS
BEGIN
DECLARE #User_ID INT
SELECT #User_ID = ID FROM AUser Where Email = #OriginalEmail
UPDATE [AUserAddress]
SET [AUser_ID] = #User_ID, [FirstName] = #FirstName, [LastName] = #LastName,
[Country_ID] = #Country_ID, [AddressLine1] = #AddressLine1,
[AddressLine2] = #AddressLine2, [AddressLine3] = #AddressLine3,
[Telephone] = #Telephone, [Email] = #Email, [City] = #City,
[State_ID] = #State_ID, [PostalCode] = #PostalCode, [Mobile] = #Mobile
WHERE
Email = #OriginalEmail
END
Called from C#:
private void UpdateAddress()
{
try
{
string strSession = objGetSession.GetEmailFromSession();
con.Open();
SqlCommand sqlCmd = new SqlCommand("usp_UpdateAddress", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("#OriginalEmail ", SqlDbType.NVarChar, 50).Value = strSession;
sqlCmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 50).Value = txtFirstName.Text;
sqlCmd.Parameters.Add("#LastName", SqlDbType.VarChar, 50).Value = txtLastName.Text;
sqlCmd.Parameters.Add("#AddressLine1", SqlDbType.VarChar, 50).Value = txtAddressLine1.Text;
sqlCmd.Parameters.Add("#AddressLine2", SqlDbType.VarChar, 50).Value = txtAddressLine2.Text;
sqlCmd.Parameters.Add("#AddressLine3", SqlDbType.VarChar, 50).Value = txtAddressLine3.Text;
sqlCmd.Parameters.Add("#Telephone", SqlDbType.VarChar, 50).Value = txtTelephone.Text;
sqlCmd.Parameters.Add("#Email", SqlDbType.NVarChar, 50).Value = txtEmailAddress.Text;
sqlCmd.Parameters.Add("#Country_ID", SqlDbType.Int).Value = ddlCountry.SelectedItem.Value;
sqlCmd.Parameters.Add("#City", SqlDbType.VarChar, 50).Value = txtCity.Text;
sqlCmd.Parameters.Add("#State_ID", SqlDbType.Int).Value = ddlState.SelectedValue.ToString();
sqlCmd.Parameters.Add("#PostalCode", SqlDbType.VarChar, 50).Value = txtPostalCode.Text;
sqlCmd.Parameters.Add("#Mobile", SqlDbType.VarChar, 50).Value = txtMobile.Text;
sqlCmd.Connection = con;
sqlCmd.ExecuteNonQuery();
con.Close();
mpeTest.Show();
Response.Write("<script> alert('Address Updated!') </script>");
}
catch (Exception e)
{
Response.Write("An Error Occurred" + e);
}
}
Is the stored procedure not executing? Debugging shows that in Update Address() it does take the new value but when execution is completed, the database is not updated...
What if you UPDATE it directly by joining the tables?
UPDATE a
SET a.[auser_id] = b.ID,
a.[firstname] = #FirstName,
a.[lastname] = #LastName,
a.[country_id] = #Country_ID,
a.[addressline1] = #AddressLine1,
a.[addressline2] = #AddressLine2,
a.[addressline3] = #AddressLine3,
a.[telephone] = #Telephone,
a.[email] = #Email,
a.[city] = #City,
a.[state_id] = #State_ID,
a.[postalcode] = #PostalCode,
a.[mobile] = #Mobile
FROM [auseraddress] a
INNER JOIN AUser b
ON a.Email = b.Email
WHERE b.email = #OriginalEmail
Your stored procedure is wrong.
According to your image the AUserAddress tables does not contain a column called Email.