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

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].

Related

Adding new parameter to stored procedure

I have a stored procedure in my database that currently takes in and utilizes 11 parameters (all working great). I need to add a new parameter to this for a new column I added.
We always explicitly define our columns in code, so there was no issue adding a column to the end of the table. However, if I add a new parameter in my stored procedure to populate this new column, will it throw an error back to my C# code if it isn't supplied, or will it default to null (or some other value) for the parameter?
Example C# code to call the stored procedure:
public static void InsertMailLog(string messageId, DateTime sentOrReceivedDate,
string fromAddress, string toAddress, string subject, string receivedMessage, string tailNumber,
string messageType, string direction, string sentOrReceived, string distributionList, ILogger AppEventLog, string filename = null)
{
List<string> lstParameterValues = new List<string>();
try
{
lstParameterValues.Add(messageId ?? "");
lstParameterValues.Add(sentOrReceivedDate.ToString("yyyy-MM-dd HH:mm:ss.fff"));
lstParameterValues.Add(fromAddress ?? "");
lstParameterValues.Add(toAddress);
lstParameterValues.Add(subject ?? "");
lstParameterValues.Add(receivedMessage ?? "");
lstParameterValues.Add(tailNumber ?? "");
lstParameterValues.Add(messageType ?? "");
lstParameterValues.Add(direction ?? "");
lstParameterValues.Add(sentOrReceived ?? "");
lstParameterValues.Add(distributionList ?? "");
lstParameterValues.Add(filename ?? ""); //THIS IS NEW, but it has not been published yet as the SP hasn't been updated.
CommonDAL.ExecSpNonQuery("spMailLogInsert", lstParameterValues);
}
catch (Exception ex)
{
CommonBLL.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, "Error", messageId, tailNumber, messageType, "", Settings.Default.ContentProvider, AppEventLog);
}
}
Example stored procedure code:
ALTER PROCEDURE [dbo].[spMailLogInsert]
#SdMessageId varchar(50),
#SentOrReceivedDate datetime,
#FromAddress varchar(100),
#ToAddress varchar(100),
#Subject varchar(255),
#Message varchar(MAX),
#TailNumber varchar(50),
#MessageType varchar(50),
#Direction varchar(50),
#SentOrReceived varchar(50),
#DistributionList varchar(50),
#Filename varchar(50) --THIS IS NEW
AS
SET NOCOUNT ON
INSERT MailLog (SdMessageId, SentOrReceivedDate, FromAddress, ToAddress,
[Subject], [Message], TailNumber, MessageType, Direction,
SentOrReceived, DistributionList, Filename --THIS IS NEW
)
VALUES (#SdMessageId, #SentOrReceivedDate, #FromAddress, #ToAddress,
#Subject, #Message, #TailNumber, #MessageType,
#Direction, #SentOrReceived, #DistributionList,
#Filename --THIS IS NEW
)
I completely understand that this is a terrible use of a stored procedure. I should be using Entity Framework, but it's already written, and I have a project to update the entire project to use EF in the DAL at a later date (this is very old code).
My question is, if I add the new parameter #Filename" to the stored procedure before the new C# code above gets published, will I get an error, or will the stored procedure parameter simply default to NULL? Or, if someone has a better way to default this to NULL or empty string, if it isn't supplied, I'm all ears.
Either Make it nullable like this.
ALTER PROCEDURE [dbo].[spMailLogInsert]
#SdMessageId varchar(50),
#SentOrReceivedDate datetime,
#FromAddress varchar(100),
#ToAddress varchar(100),
#Subject varchar(255),
#Message varchar(MAX),
#TailNumber varchar(50),
#MessageType varchar(50),
#Direction varchar(50),
#SentOrReceived varchar(50),
#DistributionList varchar(50),
#Filename varchar(50) = NULL --THIS IS NEW
......
Or Add a Default value like this:
ALTER PROCEDURE [dbo].[spMailLogInsert]
#SdMessageId varchar(50),
#SentOrReceivedDate datetime,
#FromAddress varchar(100),
#ToAddress varchar(100),
#Subject varchar(255),
#Message varchar(MAX),
#TailNumber varchar(50),
#MessageType varchar(50),
#Direction varchar(50),
#SentOrReceived varchar(50),
#DistributionList varchar(50),
#Filename varchar(50) = 'abc.txt' --THIS IS NEW
......
You could go ahead with the SP and just use a default parameter. https://technet.microsoft.com/en-US/library/ms189330(v=SQL.105).aspx
#Filename varchar(50) = NULL --THIS IS NEW
Based on your Stored Procedure it is considered required. To avoid it being required, you should add the following to your parameter:
#Filename varchar(50) = null
That will make it optional, which will allow you to avoid excessive Null checks in your code behind. Which can make your code turn to spaghetti quickly. This would be the easiest and least intrusive approach to solve your issue.
I completely understand that this is a terrible use of a stored procedure.
Er, no? It's a simple sproc, sure, but if all your SQL are sprocs, then this is the way to go.
I should be using Entity Framework [...]
Things in programming aren't always optimal, and you have to do what you have to do.
[...] if I add the new parameter "Filename" to the stored procedure before the new C# code above gets published, will I get an error, or will the SP simply default to NULL?
SQL will throw an error that the new parameter wasn't supplied through it's caller (ASP.Net). See here.
CREATE PROCEDURE Sales.uspGetSalesYTD
#SalesPerson nvarchar(50) = NULL -- NULL default value
AS
You should use a default value or it will get an error

Only a single char inserted on stored procedure Insertion

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

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 get computed column value in stored procedure

I am using ASP.NET 4.0, C# and SQL Server 2008 R2. I am getting UserName from the user in a webpage for stored in the SQL table User_Info2. Using SQL Server 2008 feature "computed column" I am generating the Vendor_ID automatically for every Insert using the stored procedure. In button click, after I insert the record I want to display the message with Vendor_ID, so please anyone tell me how to get the Vendor_ID column from the stored procedure ?
CREATE TABLE User_Info2
( SNo int Identity (2000,1) ,
Vendor_ID AS 'VEN' + CAST(SNo as varchar(16)) PERSISTED PRIMARY KEY,
UserName VARCHAR(30) NOT NULL
)
Stored procedure
ALTER PROCEDURE [dbo].[usp_User_Info2] #UserName VARCHAR(30)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO User_Info2 (UserName) VALUES (#UserName)
END
C# Code :
protected void BtnUserNext_Click(object sender, EventArgs e)
{
SqlConnection SqlCon = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_User_Info2";
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = txtUserName.Text.Trim();
cmd.Connection = SqlCon;
try
{
SqlCon.Open();
cmd.ExecuteScalar();
}
finally
{
string url = "../CompanyBasicInfo.aspx?Parameter=" + Server.UrlEncode ("+ Vendor_ID +");
ClientScript.RegisterStartupScript(this.GetType(),"callfunction",
"alert('Login created successfully for "+ Vendor_ID +"');
window.location.href = '" + url + "';", true);
SqlCon.Close();
}
}
You can output the inserted value using the OUTPUT clause, and then read it when you execute the stored procedure:
ALTER PROCEDURE [dbo].[usp_User_Info2] #UserName VARCHAR(30)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO User_Info2 (UserName)
OUTPUT Inserted.Vendor_ID
VALUES (#UserName)
END
and in your C# calling code:
object spResult;
string vendorID;
try
{
SqlCon.Open();
spResult = cmd.ExecuteScalar();
if(spResult != null) // check to make sure you got something back!
{
vendorID = spResult.ToString();
}
}
You can try this
ALTER PROCEDURE [dbo].[usp_User_Info2] #UserName VARCHAR(30)
AS
BEGIN
SET NOCOUNT ON;
declare #Id int
INSERT INTO User_Info2 (UserName) VALUES (#UserName)
SET #Id = Scope_Identity()
SELECT Vendor_ID From User_Info2 WHERE SNo = #Id
END
C#
try
{
SqlCon.Open();
string VendorID = cmd.ExecuteScalar() as string;
}
Also u can do like this
select top(1) Vendor_ID from User_Info2 order by SNo desc
You can get currently insert row with the help of SCOPE_IDENTITY()
SET #SNo = SCOPE_IDENTITY()
And below insert query you can execute select query on the #SNo
So it would be:
ALTER PROCEDURE [dbo].[usp_User_Info2]
(
#UserName VARCHAR(30),
#SNo int,
#Vendor_ID VARCHAR(50) OUTPUT
)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO User_Info2 (UserName) VALUES (#UserName)
SET #SNo = Scope_Identity()
select #Vendor_ID as Vendor_ID from User_Info2 where SNo = #SNo
END
EDIT:
SqlParameter[] param= new SqlParameter[1];
param[0] = new SqlParameter("#Vendor_ID", 0);
param[0].Direction = ParameterDirection.Output;
// Here there will be a Stored Procedure Call
int VendorID = Convert.ToInt32(param[0].Value);
So now you will #Vendor_ID which is an Output variable.

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