Stored procedure not updating sql table triggered in asp.net - c#

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

Related

System.Data.SqlClient.SqlException: 'Conversion failed when converting the nvarchar value 'STORES' to data type int.'

I am executing a stored procedure in a C# asmx webservice.
the stored procedure is as follows:
#userName NVARCHAR(50),
#password NVARCHAR(50),
#defaultTabApp NVARCHAR(20) OUT
AS
Declare #defaultTabApptemp NVARCHAR(20)
set #defaultTabApptemp ='NoAccess'
BEGIN TRANSACTION
if EXISTS(SELECT Top 1 [userId],[userName] FROM [dbo].[users] WHERE [userName]=#userName AND [password]=#password AND [AppAccess]=N'Yes')
Begin
set #defaultTabApptemp = (select Top 1 [dbo].[users].[defaultTabApp] FROM [dbo].[users] WHERE [userName]=#userName AND [password]=#password AND [AppAccess]=N'Yes')
end
select #defaultTabApp = #defaultTabApptemp
COMMIT TRANSACTION
return #defaultTabApp
my c# code is:
[WebMethod]
public string Login(string userName, string userPass)
{
string result;
SqlConnection conn = new SqlConnection(new DBConnection().ConnectionString);
try
{
SqlCommand cmd = new SqlCommand("_getSpecificUserLogin", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
}
cmd.Parameters.AddWithValue("#userName", userName);
cmd.Parameters.AddWithValue("#password", userPass);
cmd.Parameters.Add("#defaultTabApp", SqlDbType.NVarChar,20);
cmd.Parameters["#defaultTabApp"].Direction = ParameterDirection.Output;
int i = cmd.ExecuteNonQuery();
result = Convert.ToString(cmd.Parameters["#defaultTabApp"].Value);
}
finally
{
conn.Close();
}
return result;
}
i'm getting the exception found in the title on this line:int i = cmd.ExecuteNonQuery(); I tried to change it to executescalar but had the same problem. I have no int types in my stored procedure. what is the problem exactly? thanks in advance.
The bare bones of your login procedure should look something like the following.
Note, you do not need a transaction, nor do you need to check if anything exists first - that's implied by the fact it assigns a value to your output variable.
Your code doesn't handle the case where the password is incorrect, or if there are no enabled apps for the user.
In reality, you would validate the user first and assign them some sort of ticket to indicate they have logged in successfully and would not be repeatedly checking their password; when it comes time to get their default app, they are already authenticated.
You only need a top 1 if you can have a single user with more than one appAccess='Yes', in which case you are missing the ordering criteria by which it will select the correct one - without a specific order clause, the value is essentially random.
The correct syntax for an output parameter is Output
I would also hope that if this is a public facing application that the password is not plain text and is stored in the database as a hash of the user's password.
create procedure UserLogin
#userName nvarchar(50),
#password nvarchar(50), -- This should be a HASH of the user's password, performed by the application
#defaultTabApp nvarchar(20) output
as
set nocount on
set #defaultTabApp='Default failure message'
select top 1 #defaultTabApp=defaultTabApp
from dbo.Users
where AppAccess=N'Yes'
and Username=#userName and [Password]=#password
order by <<criteria if there are more than 1 matching rows>>
Go
RETURN can only return int. You already used an OUT parameter, you should remove return #defaultTabApp statement at the end of your stored procedure.
Replace
Declare #defaultTabApptemp NVARCHAR(20)
set #defaultTabApptemp ='NoAccess'
BEGIN TRANSACTION
if EXISTS(SELECT Top 1 [userId],[userName] FROM [dbo].[users] WHERE [userName]=#userName AND [password]=#password AND [AppAccess]=N'Yes')
Begin
set #defaultTabApptemp = (select Top 1 [dbo].[users].[defaultTabApp] FROM [dbo].[users] WHERE [userName]=#userName AND [password]=#password AND [AppAccess]=N'Yes')
end
select #defaultTabApp = #defaultTabApptemp
COMMIT TRANSACTION
return #defaultTabApp
with
Declare #defaultTabApptemp NVARCHAR(20)
select Top 1 #defaultTabApptemp=[dbo].[users].[defaultTabApp] FROM [dbo].[users]
WHERE [userName]=#userName AND [password]=#password AND [AppAccess]=N'Yes')
if #defaultTabApptemp is null SET #defaultTabApptemp ='NoAccess'
set #defaultTabApp = #defaultTabApptemp

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

data insert using input output stored procedure

I am creating a web application using ASP.net C#. I have a booking form and I need to insert data into a table using a Stored Procedure. The table has several columns, out of which second column is a computed column. The Stored Procedure is set up to insert the data and fetch the value from the second column after insert. Below is the code for Stored Procedure:
Create Procedure sp_InsertCashPooja
#FirstName varchar(100),
#LastName varchar(100),
#TelNo bigint,
#Star char(50),
#Rasi char(50),
#Gothram char(50),
#PDMID int,
#PayMode bit,
#PujaName char(50),
#DonateAmt decimal(19,2),
#RcptNo varchar(25) output
as
Begin
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION
if #PujaName != 'DONATION'
Begin
INSERT INTO PoojaDetails (FirstName, LastName, TelNo, Star, Rasi, Gothram, PoojaDietyMasterID, PayMode) values (#FirstName,#LastName,#TelNo,#Star,#Rasi,#Gothram,#PDMID,#PayMode)
End
if #PujaName = 'DONATION'
Begin
DECLARE #isDonate int = 0;
INSERT INTO PoojaDetails (FirstName, LastName, TelNo, Star, Rasi, Gothram, PoojaDietyMasterID, PayMode, isDonate, DonateAmount) values (#FirstName,#LastName,#TelNo,#Star,#Rasi,#Gothram,#PDMID,#PayMode, #isDonate, #DonateAmt)
End
Select #RcptNo = max(ReceiptNo) from PoojaDetails
Return #RcptNo
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF (##TRANCOUNT > 0)
ROLLBACK TRANSACTION
END CATCH
SET NOCOUNT OFF;
End
I would like to insert data on the click of a button: I was able to figure out the below code....
protected void btnSave_Click(object sender, EventArgs e)
{
frmFirstName = txtFirstName.Text.Trim().ToUpper();
frmLastName = txtLastName.Text.Trim().ToUpper();
frmPhoneNo = Convert.ToInt32(txtPhoneNo.Text.Trim());
frmNakshatra = Convert.ToString(cmbNakshatra.SelectedItem).Trim();
frmRasi = Convert.ToString(cmbRasi.SelectedItem).Trim();
frmGothram = Convert.ToString(cmbGothram.SelectedItem).Trim();
frmPujaName = Convert.ToString(cmbPujaName.SelectedItem).Trim();
using (SqlConnection connection = new SqlConnection())
{
if (frmPayMode == "Cash")
{
if (frmPujaName == "DONATION")
{
SqlDataAdapter CashAdapter = new SqlDataAdapter();
CashAdapter.InsertCommand = new SqlCommand("sp_InsertCashPooja", connection);
CashAdapter.InsertCommand.CommandType = CommandType.StoredProcedure;
Please help.... I want to capture the returning RcptNo and later intend to call another ASPX page and pass the value using a Query String.
Thanks
Use simple SqlCommand for calling your SP
connection.Open();
var cmd = new SqlCommand("sp_InsertCashPooja", connection);
cmd.Parameters.AddWithValue("FirstName", frmFirstName);
// Add all the others parameters in same way
var id = (int)cmd.ExecuteScalar();
connection.Close();
Change the return variable to:
Select #RcptNo = SCOPE_IDENTITY()
It will return the identity number created for the inserted record within this procedure.
use sql parameter..
connection = ConfigurationManager.AppSettings["mycon"];
SqlParameter[] para = new SqlParameter[2];
para[0] = new SqlParameter("#stored procedure column name", string name);
para[1] = new SqlParameter("#stored procedure column name", string name);

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