Only a single char inserted on stored procedure Insertion - c#

I am using VS 2008 Asp.net C#. To insert the data I have created a stored procedure:
ALTER PROCEDURE INS_tblRegister
#Enroll varchar,
#Name varchar,
#Dob varchar,
#Gender varchar,
#Mobile varchar,
#Address varchar,
#Branch varchar,
#Sem varchar,
#Year varchar,
#Password varchar
AS
INSERT INTO tblRegister (Enrollment, Name, Dob, Gender, Mobile, Address, Branch, Sem, Year, Password)
VALUES (#Enroll,#Name,#Dob,#Gender,#Mobile,#Address,#Branch,#Sem,#Year,#Password)
RETURN
Below is my code for button_Click :
try
{
con.Open();
cmd = new SqlCommand("INS_tblRegister",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Enroll", SqlDbType.VarChar).Value = txtEnroll.Text;
cmd.Parameters.Add("Name", SqlDbType.VarChar).Value = txtName.Text;
cmd.Parameters.Add("Dob", SqlDbType.VarChar).Value = (txtDob.Text);
cmd.Parameters.Add("Gender", SqlDbType.VarChar).Value = ddlGender.Text;
cmd.Parameters.Add("Mobile", SqlDbType.VarChar).Value = txtMobile.Text;
cmd.Parameters.Add("Address", SqlDbType.VarChar).Value = txtAddress.Text;
cmd.Parameters.Add("Branch", SqlDbType.VarChar).Value = txtBranch.Text;
cmd.Parameters.Add("Sem", SqlDbType.VarChar).Value = txtSem.Text;
cmd.Parameters.Add("Year", SqlDbType.VarChar).Value = txtYear.Text;
cmd.Parameters.Add("Password", SqlDbType.VarChar).Value = txtPassword.Text;
cmd.ExecuteNonQuery();
con.Close();
lblMsg.Text="Saved";
}
catch(Exception ex)
{
lblMsg.Visible = true;
lblMsg.Text = ex.Message;
}
This code was executed successfully but when I see the database I found :
Only the first character of my entry saved eg: look at the Gender field,I wrote Male but only M is inserted to database. Please Help me...

The default length for CHAR and VARCHAR is 1.
char and varchar (Transact-SQL)
You need to define the length of VARCHAR in the Signature
#MyField VARCHAR(100)

You need to add character lengths to your stored procedure parameters like this:
ALTER PROCEDURE INS_tblRegister
#Enroll varchar(20),#Name varchar(20),#Dob varchar(20),#Gender varchar(20),#Mobile varchar(20),#Address varchar(20), #Branch varchar(20), #Sem varchar(20), #Year varchar(20), #Password varchar(20)
AS
INSERT INTO tblRegister (Enrollment, Name, Dob, Gender, Mobile, Address, Branch, Sem, Year, Password)
VALUES (#Enroll,#Name,#Dob,#Gender,#Mobile,#Address,#Branch,#Sem,#Year,#Password)
RETURN

Declare variables of SP as #Enroll varchar(size), where size is int value. Example#Enroll varchar(500). The varchar will only consider first character since its length is 1.

Provide length of each varchar field.
ALTER PROCEDURE INS_tblRegister
#Enroll varchar(10),#Name varchar(50),
#Dob varchar(10),#Gender varchar(6),#Mobile varchar(10),#Address varchar(100),
etc...

You need to mention the size of varchar. Try this procedure.
ALTER PROCEDURE INS_tblRegister
#Enroll varchar(50),#Name varchar(50), #Dob varchar(50), #Gender varchar(50), #Mobile varchar(50), #Address varchar(50),
#Branch varchar(50), #Sem varchar(50), #Year varchar(50), #Password varchar(50)
AS
INSERT INTO tblRegister(Enrollment, Name, Dob, Gender, Mobile, Address, Branch, Sem, Year, Password) VALUES(#Enroll,#Name,#Dob,#Gender,#Mobile,#Address,#Branch,#Sem,#Year,#Password)
RETURN
The default varchar size is 1 character.

varchar[(n)]
When n is not specified in a data definition or variable declaration statement, the default length is 1.
ALTER PROCEDURE INS_tblRegister
#Enroll varchar(20),#Name varchar(20),#Dob varchar(20),#Gender varchar(20),#Mobile varchar(20),#Address varchar(20), #Branch varchar(20), #Sem varchar(20), #Year varchar(20), #Password varchar(20)
AS
INSERT INTO tblRegister (Enrollment, Name, Dob, Gender, Mobile, Address, Branch, Sem, Year, Password)
VALUES (#Enroll,#Name,#Dob,#Gender,#Mobile,#Address,#Branch,#Sem,#Year,#Password)
RETURN

Related

regdno = Convert.ToInt32(cmd.ExecuteScalar()); data not inserted [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Data is not being inserted into SQL Server using a stored procedure.
Insert code in ASP.NET / C#:
private void insert()
{
int regdno = 0;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Insert_bmsstudent"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.StoredProcedure;
string strFilename = uploadImage(photos);
cmd.Parameters.AddWithValue("#sphoto", strFilename.Trim());
cmd.Parameters.AddWithValue("#admyear", ddlyear1.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#addedddt", lbl_date.Text.Trim());
cmd.Parameters.AddWithValue("#admno", adm_no.Text.Trim());
cmd.Parameters.AddWithValue("#dateofadm", txt_dtadm.Text.Trim());
cmd.Parameters.AddWithValue("#sname", txt_sname.Text.Trim());
cmd.Parameters.AddWithValue("#preclass", ddlClass.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#presec", ddlsec.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#preroll", txt_roll.Text.Trim());
cmd.Parameters.AddWithValue("#priclass", txtpriclass.Text.Trim());
cmd.Parameters.AddWithValue("#prisec", ddlprisec.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#priroll", txt_priroll.Text.Trim());
cmd.Parameters.AddWithValue("#sgender", rdo_gender.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#sreligion", sreli.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#sdate", ddldate.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#smonth", dmonth.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#syear", ddlyear.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#caste", chk_caste.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#aadharno", txt_aadhar.Text.Trim());
cmd.Parameters.AddWithValue("#bg", txt_bg.Text.Trim());
cmd.Parameters.AddWithValue("#bplstatus", bpl_status.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#bplno", bpl_no.Text.Trim());
cmd.Parameters.AddWithValue("#svill", ddl_vill.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#spost", txt_postname.Text.Trim());
cmd.Parameters.AddWithValue("#sps", txt_ps.Text.Trim());
cmd.Parameters.AddWithValue("#sblock", txt_block.Text.Trim());
cmd.Parameters.AddWithValue("#sdist", txt_dist.Text.Trim());
cmd.Parameters.AddWithValue("#sstate", txt_state.Text.Trim());
cmd.Parameters.AddWithValue("#spincode", txt_pincode.Text.Trim());
cmd.Parameters.AddWithValue("#snationality", txt_nation.Text.Trim());
cmd.Parameters.AddWithValue("#fname", txt_fname.Text.Trim());
cmd.Parameters.AddWithValue("#fmob", txt_mobno.Text.Trim());
cmd.Parameters.AddWithValue("#foccu", txt_occu.Text.Trim());
cmd.Parameters.AddWithValue("#fqly", txt_qly.Text.Trim());
cmd.Parameters.AddWithValue("#faincome", txt_income.Text.Trim());
string strFilename2 = uploadImage2(photos2);
cmd.Parameters.AddWithValue("#fphoto", strFilename2.Trim());
cmd.Parameters.AddWithValue("#mname", txt_mother.Text.Trim());
cmd.Parameters.AddWithValue("#mmob", txt_mmobile.Text.Trim());
string strFilename3 = uploadImage3(photos3);
cmd.Parameters.AddWithValue("#mphoto", strFilename3.Trim());
cmd.Parameters.AddWithValue("#gname", txt_guar.Text.Trim());
cmd.Parameters.AddWithValue("#gmob", txt_gmob.Text.Trim());
cmd.Parameters.AddWithValue("#relative", rdorelative.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#relation1", ddl_relation1.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#rname1", txt_rname1.Text.Trim());
cmd.Parameters.AddWithValue("#rclass1", txt_rc1.Text.Trim());
cmd.Parameters.AddWithValue("#rsec1", txt_rsec1.Text.Trim());
cmd.Parameters.AddWithValue("#rroll1", txt_rroll1.Text.Trim());
cmd.Parameters.AddWithValue("#relation2", ddl_relation2.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#rname2", txt_rname2.Text.Trim());
cmd.Parameters.AddWithValue("#rclass2", txt_rc2.Text.Trim());
cmd.Parameters.AddWithValue("#rsec2", txt_rsec2.Text.Trim());
cmd.Parameters.AddWithValue("#rroll2", txt_rroll2.Text.Trim());
cmd.Parameters.AddWithValue("#relation3", ddl_relation3.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#rclass3", txt_rc3.Text.Trim());
cmd.Parameters.AddWithValue("#rsec3", txt_rsec3.Text.Trim());
cmd.Parameters.AddWithValue("#rroll3", txt_rroll3.Text.Trim());
cmd.Parameters.AddWithValue("#bankname", ddl_bank.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#bbranch", txt_branch.Text.Trim());
cmd.Parameters.AddWithValue("#bifsc", txt_ifsc.Text.Trim());
cmd.Parameters.AddWithValue("#baccount", txt_baccount.Text.Trim());
cmd.Parameters.AddWithValue("#agree", declarationchk.Text.Trim());
cmd.Parameters.AddWithValue("#other1", other1.Text.Trim());
cmd.Parameters.AddWithValue("#other2", other2.Text.Trim());
cmd.Parameters.AddWithValue("#other3", other3.Text.Trim());
cmd.Parameters.AddWithValue("#other4", other4.Text.Trim());
cmd.Parameters.AddWithValue("#other5", other5.Text.Trim());
cmd.Parameters.AddWithValue("#other6", other6.Text.Trim());
cmd.Connection = con;
con.Open();
regdno = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
}
string message = string.Empty;
switch (regdno)
{
case -1:
message = "Student already exists.\\nEntered Students roll no. already been used. Please Enter a different roll no..";
break;
case -2:
message = "Supplied Account No. has already been used.";
break;
default:
message = "Registration successful. \\nYour Regd. no: " + regdno.ToString();
break;
}
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
lblmsg.Text = regdno.ToString();
string queryString = "http://example.org/admin/studentdetailspopup.aspx?userid=" + lblmsg.Text.Trim();
string newWin = "window.open('" + queryString + "');";
ClientScript.RegisterStartupScript(this.GetType(), "pop", newWin, true);
}
}
#endregion
Stored procedure :
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Insert_bmsstudent]
#admyear NVARCHAR(50),
#addedddt DATE,
#admno NVARCHAR(50),
#dateofadm DATE,
#sname NVARCHAR(100),
#preclass NVARCHAR(50),
#presec NVARCHAR(50),
#preroll NVARCHAR(50),
#priclass NVARCHAR(50),
#prisec NVARCHAR(50),
#priroll NVARCHAR(50),
#sgender VARCHAR(50),
#sreligion VARCHAR(50),
#sdate NVARCHAR(50),
#smonth NVARCHAR(50),
#syear NVARCHAR(50),
#caste VARCHAR(50),
#sphoto NVARCHAR(50),
#aadharno NVARCHAR(50),
#bg NVARCHAR(50),
#bplstatus NVARCHAR(50),
#bplno NVARCHAR(50),
#svill VARCHAR(500),
#spost VARCHAR(50),
#sps VARCHAR(50),
#sblock VARCHAR(50),
#sdist VARCHAR(50),
#sstate VARCHAR(50),
#spincode VARCHAR(50),
#snationality VARCHAR(50),
#fname VARCHAR(250),
#fmob VARCHAR(50),
#foccu VARCHAR(50),
#fqly VARCHAR(50),
#faincome VARCHAR(50),
#fphoto VARCHAR(50),
#mname VARCHAR(50),
#mmob VARCHAR(50),
#mphoto VARCHAR(50),
#gname VARCHAR(50),
#gmob VARCHAR(50),
#relative VARCHAR(50),
#relation1 VARCHAR(50),
#rname1 VARCHAR(50),
#rclass1 VARCHAR(50),
#rsec1 VARCHAR(50),
#rroll1 VARCHAR(50),
#relation2 VARCHAR(50),
#rname2 VARCHAR(50),
#rclass2 VARCHAR(50),
#rsec2 VARCHAR(50),
#rroll2 VARCHAR(50),
#relation3 VARCHAR(50),
#rclass3 VARCHAR(50),
#rsec3 VARCHAR(50),
#rroll3 VARCHAR(50),
#bankname VARCHAR(500),
#bbranch NVARCHAR(500),
#bifsc NVARCHAR(50),
#baccount NVARCHAR(50),
#agree VARCHAR(50),
#other1 NVARCHAR(500),
#other2 NVARCHAR(500),
#other3 NVARCHAR(500),
#other4 NVARCHAR(500),
#other5 NVARCHAR(500),
#other6 NVARCHAR(500)
--#TaskParam int,
-- #Del int,
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT slno FROM fbmssms.bmsstudents WHERE preroll = #preroll)
BEGIN
SELECT -1 -- Username exists.
END
ELSE IF EXISTS(SELECT slno FROM fbmssms.bmsstudents WHERE baccount = #baccount)
BEGIN
SELECT -2 -- Email exists.
END
ELSE
BEGIN
INSERT INTO [fbmssms.bmsstudents]([admyear], [nvarchar], [addedddt], [admno], [dateofadm], [sname],
[preclass], [presec], [preroll], [priclass], [prisec], [priroll],
[sgender], [sreligion], [sdate], [smonth], [syear], [caste],
[sphoto], [aadharno], [bg], [bplstatus], [bplno], [svill],
[spost], [sps], [sblock], [sdist], [sstate], [spincode], [snationality],
[fname], [fmob], [foccu], [fqly], [faincome], [fphoto], [mname],
[mmob], [mphoto], [gname], [gmob], [relative], [relation1],
[rname1], [rclass1], [rsec1], [rroll1], [relation2], [rname2], [rclass2],
[rsec2], [rroll2], [relation3], [rclass3], [rsec3], [rroll3],
[bankname], [bbranch], [bifsc], [baccount], [agree],
[other1], [other2], [other3], [other4], [other5], [other6])
VALUES (#admyear, #addedddt, #admno, #dateofadm, #sname,
#preclass, #presec, #preroll, #priclass, #prisec, #priroll,
#sgender, #sreligion, #sdate, #smonth, #syear, #caste,
#sphoto, #aadharno, #bg, #bplstatus, #bplno, #svill,
#spost, #sps, #sblock, #sdist, #sstate, #spincode, #snationality,
#fname, #fmob, #foccu, #fqly, #faincome, #fphoto, #mname,
#mmob, #mphoto, #gname, #gmob, #relative, #relation1,
#rname1, #rclass1, #rsec1, #rroll1, #relation2, #rname2, #rclass2,
#rsec2, #rroll2, #relation3, #rclass3, #rsec3, #rroll3,
#bankname, #bbranch, #bifsc, #baccount, #agree,
#other1, #other2, #other3, #other4, #other5, #other6)
SELECT SCOPE_IDENTITY()
END
END
Error....................
Invalid object name 'fbmssms.bmsstudents'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'fbmssms.bmsstudents'.
Source Error:
Line 436: cmd.Connection = con;
Line 437: con.Open();
Line 438: regdno = Convert.ToInt32(cmd.ExecuteScalar());
Line 439: con.Close();
Line 440: }
Connection was there. Even my same coding is running in another page in same style. Here I don't know why it is not working.
INSERT INTO [fbmssms.bmsstudents] ... Invalid object name 'fbmssms.bmsstudents'.
There are a few possibilities here. As written, the INSERT statement is pointing to a table named [fbmssms.bmsstudents] in whatever database the connection object points to.
If you actually mean table bmsstudents in schema fbmssms, use [fbmssms].[bmsstudents].
If you mean table bmsstudents in the default schema in database fbmssms, use [fbmssms]..[bmsstudents] or [fbmssms].[dbo].[bmsstudents] (assumes that dbo is the default schema for the database).
If you mean the table named [fbmssms.bmsstudents], you are probably connected to an incorrect database. Add the database name and schema to the table name, e.g. [MyDatabase].[dbo].[fbmssms.bmsstudents].

Stored procedure called from form returns duplicate row error, but the record does not exist in table, what's going on?

I am getting the following error when calling a stored procedure from a Windows Form's button click.
Cannot insert duplicate key row in object 'dbo.User' with unique index 'IX_User_Username'. The duplicate key value is (someusername).
However, my table is empty, so there shouldn't be a duplicate key row error.
The stored procedure does work correctly if I execute it directly from Visual Studio by right-clicking the Stored Procedure and then Execute, I then type in the values and it executes correctly.
I am using
Visual Studio Community Edition 2019
SQL Server Express
.NET 4.7.03190
Here is the User object - this model takes in user's first and last names, username, passwords and handles password hashing and salts.
The Create() method inserts calls the stored procedure.
public User(String firstName, String lastName, string username, string password)
{
this.firstName = firstName;
this.lastName = lastName;
this.username = username;
Password newPassword = new Password(password);
newPassword.Hash();
this.password = newPassword.GetHashedPassword();
this.salt = newPassword.GetSalt();
this.loginAttempts = 0;
this.locked = false;
}
public void Create()
{
database = new Database();
using (SqlConnection conn = database.GetSqlConnection())
{
using (SqlCommand command = new SqlCommand("CreateUserStoredProcedure", conn))
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddWithValue("#firstName", this.firstName);
command.Parameters.AddWithValue("#lastName", this.lastName);
command.Parameters.AddWithValue("#username", this.username);
command.Parameters.AddWithValue("#password", this.password);
command.Parameters.AddWithValue("#salt", this.salt);
command.Parameters.AddWithValue("#loginAttempts", this.loginAttempts);
command.Parameters.AddWithValue("#locked", this.locked);
conn.Open();
command.ExecuteNonQuery();
using (SqlDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
// returns the result for testing
Console.WriteLine("From Reader - ");
Console.WriteLine(reader["Return Value"]);
}
}
}
}
}
And here's the stored procedure:
CREATE PROCEDURE [dbo].[CreateUserStoredProcedure]
#firstName NVARCHAR(50),
#lastName NVARCHAR(50),
#username NVARCHAR(50),
#password NVARCHAR(36),
#salt NVARCHAR(255),
#loginAttempts INT = 0,
#locked BIT = 0
AS
BEGIN
DECLARE #Id INT
INSERT INTO [dbo].[Users]
VALUES (#username)
SET #Id = (SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY])
INSERT INTO [dbo].[People] (User_Id, FirstName, LastName)
VALUES (#Id, #firstName, #lastName)
INSERT INTO [dbo].[Credentials] (User_Id, "Password", Salt, LoginAttempts, Locked)
VALUES (#Id, #password, #salt, #loginAttempts, #locked)
RETURN 1
END
Table structure is simple:
User (Id, Username) (Unique Index 'IX_User_Username')
People (User_Id, FirstName, LastName) (FK User_Id > User.Id)
Credentials (User_Id, Password, Salt, LoginAttempts, Locked) (FK User_Id > User.ID)
I am expecting the new user to be added from the form, from given input data, just as it does when executing the stored procedure directly.
I have tested in the Create() method by using Console.WriteLine() for each input data to make sure that I am sending the correct values to the stored procedure. Surely, the username is getting sent correctly:
Can you help me to determine the issue? Thanks.
EDIT:
Stored Procedure
CREATE PROCEDURE [dbo].[CreateUserStoredProcedure]
#firstName nvarchar(50),
#lastName nvarchar(50),
#username nvarchar(50),
#password nvarchar(36),
#salt nvarchar(255),
#loginAttempts int = 0,
#locked bit = 0
AS
BEGIN TRY
BEGIN TRANSACTION
DECLARE
#Id int
INSERT INTO [dbo].[User]
VALUES
(#username)
SET #Id = (SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY])
--SET #Id = (SELECT Id FROM [dbo].[User] WHERE Username = #username)
INSERT INTO [dbo].[Person]
(User_Id, FirstName, LastName)
VALUES
(#Id, #firstName, #lastName)
INSERT INTO [dbo].[Credential]
(User_Id, "Password", Salt, LoginAttempts, Locked)
VALUES
(#Id, #password, #salt, #loginAttempts, #locked)
RETURN 1
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF(##TRANCOUNT > 0)
ROLLBACK TRANSACTION
RAISERROR ('User could not be created', 0, 0);
END CATCH

Could not insert complete values into database using stored procedure?

I'm very new to using stored procedure in C#. But m unable to insert the values into database completely?
create procedure insertPro
(#name as varchar,
#lname as varchar,
#phone as varchar)
as
insert into std_info
values (#name, #lname, #phone)
go
And here is my C# code
SqlConnection con = new SqlConnection("Data Source=xxxxxxxx;Integrated Security=SSPI;Initial Catalog=xxxxx");
SqlCommand cmd = new SqlCommand("insertPro",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = textBox1.Text;
cmd.Parameters.Add("#lname", SqlDbType.VarChar).Value = textBox2.Text;
cmd.Parameters.Add("#phone", SqlDbType.VarChar).Value = textBox3.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
This insert values into database but not completely for example, if i insert first name as abc then it only insert a and same for the last name and phone?
Put a length on your parameters:
create procedure insertPro(
#name as varchar(30),
#lname as varchar(30),
#phone as varchar(30)
Change your stored procedure to:
create procedure insertPro
(
#name as varchar(max), //change (max) to maximum constraint length you set for each column
#lname as varchar(max),
#phone as varchar(max)
)
as
insert into std_info values (#name,#lname,#phone)
#name as varchar
So using simple varchar without any length specified. It takes only single character. So that's why you are seeing only one character in your table. You just need to specify them with length equal to length of the column.
#name as varchar(100)

Stored procedure not updating sql table triggered in asp.net

I've got site where a table will show a list of assets and their information pulled from a table in sql. I've got a section button where, if necessary, a clerk is able to press and modify existing information by inputting the new within a text or drop down field. This is done using a stored procedure; everything seems to be running well until you check the work, nothing's been updated!
Here is the code for editing the information;
protected void ADD_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["DATASYSTEMS"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("UPDATING_ASSETS", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ASSET_NUMBER", Txtasset_number.Text);
cmd.Parameters.AddWithValue("#MACHINE_NAME", Txtmachine_name.Text);
cmd.Parameters.AddWithValue("#PORT_NUMBER", Txtport_number.Text);
cmd.Parameters.AddWithValue("#BUILDING_NUMBER", DPBUILDING.SelectedValue);
cmd.Parameters.AddWithValue("#ROOM_NUMBER", Txtroom_number.Text);
cmd.Parameters.AddWithValue("#TELEPHONE_NUMBER", Txttelephone_number.Text);
cmd.Parameters.AddWithValue("#FLOOR", Txtfloor.Text);
cmd.Parameters.AddWithValue("#SERIAL", Txtserial.Text);
cmd.Parameters.AddWithValue("#TYPE", DPTYPE.SelectedValue);
cmd.Parameters.AddWithValue("#BRANCH", DPBRANCH.SelectedValue);
cmd.Parameters.AddWithValue("#SECTION", DPSECTION.SelectedValue);
cmd.Parameters.AddWithValue("#USERS", txtuser1.Text);
ClientScript.RegisterClientScriptBlock(this.GetType(), "key", "<script type='text/javascript'>alert('Record has been updated.');window.location='navigation.aspx';</script>");
}
}
protected void dglocaltables_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
and here is the stored procedure that is supposed to update.
CREATE PROCEDURE [dbo].[update_TBL_INFO_1] #ASSET_NUMBER as nvarchar(50), #PORT_NUMBER as nvarchar(50), #MACHINE_NAME as nvarchar(50), #TYPE as nvarchar(50) , #BRANCH as nvarchar(50), #SECTION as nvarchar(50), #BUILDING_NUMBER as nvarchar(50), #ROOM_NUMBER as nvarchar(50), #TELEPHONE_NUMBER as nvarchar (50), #FLOOR as nvarchar (50), #USERS as nvarchar (50), #ID as float (8), #SERIAL as nvarchar (50) as
If (SELECT ASSET_NUMBER FROM dbo.TBL_INFO WHERE ASSET_NUMBER=#ASSET_NUMBER AND [ID]=#ID)=#ASSET_NUMBER
BEGIN
If (SELECT MACHINE_NAME FROM dbo.TBL_INFO WHERE MACHINE_NAME=#MACHINE_NAME AND [ID]=#ID)=#MACHINE_NAME
BEGIN
If (SELECT PORT_NUMBER FROM dbo.TBL_INFO WHERE PORT_NUMBER=#PORT_NUMBER AND [ID]=#ID)=#PORT_NUMBER
BEGIN
If (SELECT [ID] FROM dbo.TBL_INFO WHERE [ID]=#ID)=#ID
BEGIN
UPDATE dbo.TBL_INFO
SET
dbo.TBL_INFO.ASSET_NUMBER = #ASSET_NUMBER,
dbo.TBL_INFO.MACHINE_NAME = #MACHINE_NAME,
dbo.TBL_INFO.PORT_NUMBER = #PORT_NUMBER,
dbo.TBL_INFO.BUILDING_NUMBER = #BUILDING_NUMBER,
dbo.TBL_INFO.ROOM_NUMBER = #ROOM_NUMBER,
dbo.TBL_INFO.TELEPHONE_NUMBER = #TELEPHONE_NUMBER,
dbo.TBL_INFO.[FLOOR]= #FLOOR,
dbo.TBL_INFO.TYPE = #TYPE,
dbo.TBL_INFO.BRANCH = #BRANCH,
dbo.TBL_INFO.[SECTION] = #SECTION,
dbo.TBL_INFO.USERS = #USERS,
dbo.TBL_INFO.[ID] = #ID,
dbo.TBL_INFO.SERIAL = #SERIAL
WHERE dbo.TBL_INFO.ASSET_NUMBER=#ASSET_NUMBER
INSERT INTO dbo.TBL_INFO (ASSET_NUMBER, MACHINE_NAME, PORT_NUMBER, BUILDING_NUMBER, ROOM_NUMBER, TELEPHONE_NUMBER, [FLOOR], TYPE, BRANCH, [SECTION], USERS, SERIAL, [ID]) VALUES (#ASSET_NUMBER, #MACHINE_NAME, #PORT_NUMBER, #BUILDING_NUMBER, #ROOM_NUMBER, #TELEPHONE_NUMBER, #FLOOR, #TYPE, #BRANCH, #SECTION, #USERS, #SERIAL, #ID)
SELECT #ID, ACCESS='VALID'
END
ELSE
BEGIN
SELECT #ID, ACCESS='INVALID'
END
END
ELSE
BEGIN
SELECT ACCESS='RESTRICTED'
END
END
ELSE
BEGIN
SELECT ACCESS='DENIED'
END
END
GO
where am I going wrong?
You never execute the command!
You need this at the end of all those .AddWithValue() calls:
cmd.ExecuteNonQuery();

How to save data in a table with multiple foreign keys while using a stored procedure in C#

I have a table Item_Order with the columns
orderId, clintName, companyName, itemName, orderDate, qauntity, clintId_FK, itemId_FK, status
where clintId_FK and item_FK are the primary keys of the Clint and Item_Configuration tables, respectively.
I have created a stored procedure for an insert record in the Item_Order table. i.e.
ALTER PROCEDURE [dbo].[Order_Create_SP]
#orderId varchar(50),
#clintName varchar(50),
#companyName varchar(50),
#itemName varchar(50),
#orderDate datetime,
#qauntity int,
#status char(10),
#operation int
AS
DECLARE #id1 varchar(50)
DECLARE #id2 varchar(50)
BEGIN
SET NOCOUNT ON;
if #operation = 0
BEGIN
SELECT top(1)#id1 = clintId FROM dbo.Clint order by clintId desc
select top(1)#id2 = itemId from dbo.Item_Configuration order by itemId desc
insert into Item_Order(orderId, clintName, companyName, itemName, orderDate, qauntity, clintId_FK, itemId_FK, status)
values(#orderId, #clintName, #companyName, #itemName, #orderDate, #qauntity, #id1, #id2, 'OPEN')
END
END
and my C# code is
private void btnOrder_Click(object sender, EventArgs e)
{
SqlConnection conn1 = new SqlConnection();
try
{
SqlCommand inserOrder= new SqlCommand("Order_Create_SP", conn1);
inserOrder.CommandType = CommandType.StoredProcedure;
inserOrder.Parameters.Add("#orderId", SqlDbType.VarChar);
inserOrder.Parameters["#orderId"].Value = oredrId.Text;
inserOrder.Parameters.Add("#clintName", SqlDbType.VarChar);
inserOrder.Parameters["#clintName"].Value = comboClint.Text;
inserOrder.Parameters.Add("#itemName", SqlDbType.VarChar);
inserOrder.Parameters["#itemName"].Value = comboItem.Text;
inserOrder.Parameters.Add("#orderDate", SqlDbType.DateTime);
inserOrder.Parameters["#orderDate"].Value=Convert.ToDateTime(orderDate.Text);
inserOrder.Parameters.Add("#qauntity", SqlDbType.Int);
inserOrder.Parameters["#qauntity"].Value = Convert.ToInt32(qauntity.Text);
inserOrder.Parameters.Add("#stauts", SqlDbType.VarChar);
inserOrder.Parameters["#stauts"].Value = "OPEN";
inserOrder.Parameters.Add("#companyName", SqlDbType.VarChar);
inserOrder.Parameters["#companyName"].Value = companyName.Text;
inserOrder.Parameters.Add("#operation", SqlDbType.VarChar);
inserOrder.Parameters["#operation"].Value = 0;
inserOrder.ExecuteNonQuery();
I am doing something that is not compatible? It is not working properly. Please help.
Thank you.
Not sure if this is your problem or not, but your stored procedure is missing WHERE clauses when looking up the foreign keys. Try changing to something like
SELECT top(1)#id1 = clintId FROM dbo.Clint WHERE Name = #clintName order by clintId desc
SELECT top(1)#id2 = itemId from dbo.Item_Configuration WHERE name = #itemName order by itemId desc

Categories