Related
I am looking to Insert a row into a table and return the Identity column in c# code. I cannot seem to get the syntax quite right.
Here is the storted procedure
ALTER PROCEDURE [dbo].[sp_InsertIssue]
#Application nchar(20) = NULL ,
#Version nchar(10) = NULL ,
#CreatedBy NVARCHAR(30) = NULL ,
#AssignedTo nVARCHAR(max) = NULL ,
#Description nVARCHAR(max) = NULL ,
#UserId INT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.Issue
(
Application ,
Version ,
CreatedBy ,
AssignedTo ,
Description ,
UserId
)
VALUES
(
#Application ,
#Version ,
#CreatedBy ,
#AssignedTo ,
#Description ,
#UserId
)
RETURN SCOPE_IDENTITY()
END
Here is the C# Code
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "sp_InsertIssue ";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Connection = m_Connection;
SqlParameter parm = new SqlParameter("#IssueId", SqlDbType.Int);
parm.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add("#Application", SqlDbType.VarChar).Value = p_Application;
cmd.Parameters.Add("#Version", SqlDbType.VarChar).Value = p_Version;
cmd.Parameters.Add("#CreatedBy", SqlDbType.VarChar).Value = p_CreatedBy;
cmd.Parameters.Add("#AssignedTo", SqlDbType.VarChar).Value = p_AssignedTo;
cmd.Parameters.Add("#Description", SqlDbType.VarChar).Value = p_Description;
cmd.Parameters.Add("#UserId", SqlDbType.Int).Value = p_UserId;
var returnParameter = cmd.Parameters.Add("IssueId", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
/// send data to db
Int32 id = (int)cmd.ExecuteNonQuery();
Return -1 not the identity column
You have to make some changes :
SELECT SCOPE_IDENTITY() is beter than Return SCOPE_IDENTITY()
in your code you have to change also cmd.ExecuteNonQuery()
with int id = Convert.ToInt32(cmd.ExecuteScalar());
Changing my answer completely after reading your code more closely :) You were so close
Change:
Int32 id = (int)cmd.ExecuteNonQuery();
To:
cmd.ExecuteNonQuery(); // this returns the # of "rows affected"
Int32 id = (int)returnParameter.Value
I am having an issue with the code below, I keep getting
"Procedure or function 'InsertFile' Expects parameter '#ID', which was
not supplied"
I must be doing something wrong in the returning of the ID.
ALTER PROCEDURE [dbo].[InsertFile]
-- Add the parameters for the stored procedure here
--#AssetID INT,
#ComputerName varchar(max),
#FilePath varchar(max),
#Owner varchar(100),
#Size int,
#Extension varchar(50),
#CreationDate datetime,
#ModifiedDate datetime,
#AccessedDate datetime,
#ID int output
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF NOT EXISTS (SELECT * From DC_Files Where computerName = #ComputerName AND FilePath = #FilePath)
BEGIN
INSERT INTO DC_Files (ComputerName, FilePath, Owner, Size, Extension, CreationDate, ModifiedDate, AccessedDate)
VALUES (#ComputerName, #FilePath, #Owner, #Size, #Extension, #CreationDate, #ModifiedDate, #AccessedDate)
END
ELSE
BEGIN
UPDATE DC_Files
SET Owner = #Owner, Size = #Size, CreationDate = #CreationDate, ModifiedDate = #ModifiedDate, AccessedDate = #AccessedDate
WHERE computerName = #ComputerName AND FilePath = #FilePath
END
SET #ID = SCOPE_IDENTITY()
END
The C# code:
SqlCommand cmd = new SqlCommand("InsertFile",conn);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("#AssetID", FileInfo);
cmd.Parameters.AddWithValue("#ComputerName", Environment.MachineName);
cmd.Parameters.AddWithValue("#FilePath", FilePath);
cmd.Parameters.AddWithValue("#Owner", FileSecurity.GetOwner(typeof(NTAccount)).Value);
cmd.Parameters.AddWithValue("#Size", FileInfo.Length);
cmd.Parameters.AddWithValue("#Extension", FileInfo.Extension);
cmd.Parameters.AddWithValue("#CreationDate", FileCreationTime);
cmd.Parameters.AddWithValue("#ModifiedDate", FileModifiedTime);
cmd.Parameters.AddWithValue("#AccessedDate", FileAccessedTime);
var returnParameter = cmd.Parameters.Add("#ID", SqlDbType.Int);
cmd.ExecuteNonQuery();
You have to set the Direction to Output since by default the Direction of all Parameter is Input.
// Create parameter with Direction as Output
SqlParameter returnParameter = new SqlParameter("#ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(returnParameter);
Try Adding output parameter as follows in ur C# code
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = "#ID";
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);
I got the error:
Procedure or function usp_User_Info3 has too many arguments specified
When I run the program. I don't know the error in SP or in C# code. I have to display the Vendor_ID after the user clicks the submit button. Where the thing going wrong here ?
Table structure :
CREATE TABLE User_Info3
(
SNo int Identity (2000,1) ,
Vendor_ID AS 'VEN' + CAST(SNo as varchar(16)) PERSISTED PRIMARY KEY,
UserName VARCHAR(16) NOT NULL,
User_Password VARCHAR(12) NOT NULL,
User_ConPassword VARCHAR(12) NOT NULL,
User_FirstName VARCHAR(25) NOT NULL,
User_LastName VARCHAR(25) SPARSE NULL,
User_Title VARCHAR(35) NOT NULL,
User_EMail VARCHAR(35) NOT NULL,
User_PhoneNo VARCHAR(14) NOT NULL,
User_MobileNo VARCHAR(14)NOT NULL,
User_FaxNo VARCHAR(14)NOT NULL,
UserReg_Date DATE DEFAULT GETDATE()
)
Stored Procedure :
ALTER PROCEDURE [dbo].[usp_User_Info3]
#SNo INT OUTPUT,
#Vendor_ID VARCHAR(10) OUTPUT,
#UserName VARCHAR(30),
#User_Password VARCHAR(12),
#User_ConPassword VARCHAR(12),
#User_FirstName VARCHAR(25),
#User_LastName VARCHAR(25),
#User_Title VARCHAR(35),
#User_OtherEmail VARCHAR(30),
#User_PhoneNo VARCHAR(14),
#User_MobileNo VARCHAR(14),
#User_FaxNo VARCHAR(14)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO User_Info3 (UserName,User_Password,User_ConPassword,User_FirstName,
User_LastName,User_Title,User_OtherEmail,User_PhoneNo,User_MobileNo,User_FaxNo)
VALUES (#UserName,#User_Password,#User_ConPassword,#User_FirstName,#User_LastName,
#User_Title,#User_OtherEmail,#User_PhoneNo,#User_MobileNo,#User_FaxNo)
SET #SNo = Scope_Identity()
SELECT Vendor_ID From User_Info3 WHERE SNo = #SNo
END
C# Code :
protected void BtnUserNext_Click(object sender, EventArgs e)
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_User_Info3";
System.Data.SqlClient.SqlParameter SNo=cmd.Parameters.Add("#SNo",System.Data.SqlDbType.Int);
System.Data.SqlClient.SqlParameter Vendor_ID=cmd.Parameters.Add("#Vendor_ID",
System.Data.SqlDbType.VarChar,10);
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = txtUserName.Text;
cmd.Parameters.Add("#User_Password", SqlDbType.VarChar).Value = txtRegPassword.Text;
cmd.Parameters.Add("#User_ConPassword", SqlDbType.VarChar).Value = txtRegConPassword.Text;
cmd.Parameters.Add("#User_FirstName", SqlDbType.VarChar).Value = txtRegFName.Text;
cmd.Parameters.Add("#User_LastName", SqlDbType.VarChar).Value = txtRegLName.Text;
cmd.Parameters.Add("#User_Title", SqlDbType.VarChar).Value = txtRegTitle.Text;
cmd.Parameters.Add("#User_OtherEmail", SqlDbType.VarChar).Value = txtOtherEmail.Text;
cmd.Parameters.Add("#User_PhoneNo", SqlDbType.VarChar).Value =txtRegTelephone.Text;
cmd.Parameters.Add("#User_MobileNo", SqlDbType.VarChar).Value =txtRegMobile.Text;
cmd.Parameters.Add("#User_FaxNo", SqlDbType.VarChar).Value =txtRegFax.Text;
cmd.Connection = SqlCon;
try
{
Vendor_ID.Direction = System.Data.ParameterDirection.Output;
SqlCon.Open();
cmd.ExecuteNonQuery();
string VendorID = cmd.ExecuteScalar() as string;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
string url = "../CompanyBasicInfo.aspx?Parameter=" + Server.UrlEncode(" + VendorID + ");
SqlCon.Close();
}
}
You're not setting the direction of the #SNo parameter
You're calling the command twice - Just call it with ExecuteScalar if you want the return value.
You're not setting the value of your #Vendor_ID output parameter in the stored procedure.
If I had to guess, I would wager that cmd is being re-used and has parameters from a previous call left in it. One option would be to call cmd.Parameters.Clear(), but frankly I see little point re-using this SqlCommand instance - it would be better to use a new command each time:
using(var cmd = SqlCon.CreateCommand()) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_User_Info3";
// TODO: add parameters
// TODO: call one of the Execute* methods
}
User_OtherEmail column doesnt exist in the table
Correct Stored Procedure
Create PROCEDURE [dbo].[usp_User_Info3]
#SNo INT OUTPUT,
#Vendor_ID VARCHAR(10) OUTPUT,
#UserName VARCHAR(30),
#User_Password VARCHAR(12),
#User_ConPassword VARCHAR(12),
#User_FirstName VARCHAR(25),
#User_LastName VARCHAR(25),
#User_Title VARCHAR(35),
#User_Email VARCHAR(30),
#User_PhoneNo VARCHAR(14),
#User_MobileNo VARCHAR(14),
#User_FaxNo VARCHAR(14)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO User_Info3 (UserName,User_Password,User_ConPassword,User_FirstName,
User_LastName,User_Title,User_Email,User_PhoneNo,User_MobileNo,User_FaxNo)
VALUES (#UserName,#User_Password,#User_ConPassword,#User_FirstName,#User_LastName,
#User_Title,#User_Email,#User_PhoneNo,#User_MobileNo,#User_FaxNo)
SET #SNo = Scope_Identity()
SELECT Vendor_ID From User_Info3 WHERE SNo = #SNo
END
and the c# code to be modified accordingly .
After all these answers from great minds I can't believe you are still stuck. Here are my suggestions
In your PROC
'maintain this in your parameter
#Vendor_ID VARCHAR(10) OUTPUT,
Update to Select VendorID into #VendorID. See the second line
SET #SNo = Scope_Identity()
SELECT #Vendor_ID=VendorID From User_Info3 WHERE SNo = #SNo
In C#, do not call ExecuteScalar use ExecuteNonQuery
string newVendorID = "";
try
{
Vendor_ID.Direction = System.Data.ParameterDirection.Output;
SqlCon.Open();
cmd.ExecuteNonQuery();
if(Vendor_ID.Value != null)
newVendorID = Vendor_ID.Value.ToString();
}
You could rename the Vendor_ID parameter to something more meaningful, like VendorIDParam. Hope this helps?
Thanks for all your response.After i modify many times the C# code and SP according to your ideas, finally i got the answer for my question. I removed 'Vendor_ID' from my SP and add few codes in my code as shown below.
Stored procedure :
ALTER PROCEDURE [dbo].[usp_User_Info3]
#SNo INT OUTPUT,
#UserName VARCHAR(30),
#User_Password VARCHAR(12),
#User_ConPassword VARCHAR(12),
#User_FirstName VARCHAR(25),
#User_LastName VARCHAR(25),
#User_Title VARCHAR(35),
#User_OtherEmail VARCHAR(30),
#User_PhoneNo VARCHAR(14),
#User_MobileNo VARCHAR(14),
#User_FaxNo VARCHAR(14)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO User_Info3 (UserName,User_Password,User_ConPassword,User_FirstName,User_Title,User_OtherEmail,User_PhoneNo,User_MobileNo,User_FaxNo)
VALUES (#UserName,#User_Password,#User_ConPassword,#User_FirstName,#User_LastName,#User_Title,#User_OtherEmail,#User_PhoneNo,#User_MobileNo,#User_FaxNo)
SET #SNo = Scope_Identity()
END
C# Code :
protected void BtnUserNext_Click(object sender, EventArgs e)
{
SqlCon.Open();
SqlCommand cmd2 = new SqlCommand("usp_User_Info3", SqlCon);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "usp_User_Info3";
System.Data.SqlClient.SqlParameter SNo=cmd2.Parameters.Add("#SNo", System.Data.SqlDbType.Int);
cmd2.Parameters.Add("#UserName", SqlDbType.VarChar).Value = txtUserName.Text.Trim();
cmd2.Parameters.Add("#User_Password", SqlDbType.VarChar).Value = txtRegPassword.Text.Trim();
cmd2.Parameters.Add("#User_ConPassword", SqlDbType.VarChar).Value = txtRegConPassword.Text;
cmd2.Parameters.Add("#User_FirstName", SqlDbType.VarChar).Value = txtRegFName.Text.Trim();
cmd2.Parameters.Add("#User_LastName", SqlDbType.VarChar).Value = txtRegLName.Text.Trim();
cmd2.Parameters.Add("#User_Title", SqlDbType.VarChar).Value = txtRegTitle.Text.Trim();
cmd2.Parameters.Add("#User_OtherEmail", SqlDbType.VarChar).Value = txtOtherEmail.Text.Trim();
cmd2.Parameters.Add("#User_PhoneNo", SqlDbType.VarChar).Value = txtRegCode1.Text;
cmd2.Parameters.Add("#User_MobileNo", SqlDbType.VarChar).Value = txtRegCode2.Text;
cmd2.Parameters.Add("#User_FaxNo", SqlDbType.VarChar).Value = txtRegCode3.Text;
cmd2.Connection = SqlCon;
try
{
SNo.Direction = System.Data.ParameterDirection.Output;
cmd2.ExecuteScalar();
string VendorID = "VEN" + cmd2.Parameters["#SNo"].Value.ToString();
}
finally
{
string url = "../CompanyBasicInfo.aspx?Parameter=" + Server.UrlEncode(" + VendorID + ");
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Login created successfully');window.location.href = '" + url + "';", true);
SqlCon.Close();
}
}
I have a stored procedure on my server that inserts some parameters and returns the ID that was inserted. I am writing a form to do this easily but I cannot seem to get the parameter which is passed back.
To save you doing a whole bunch of possibly pointless reading, it's probably better to just pay attention to my C# code and let me know what I need to do in order to pass parameters and get one in return.
C# Default.aspx
connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionInfo"]);
sql = "aStoredProc";
command = new SqlCommand(sql, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameter.Add(new SqlParameter("#FirstName", SqlDbType.VarChar)).Value = sFirstname;
command.Parameter.Add(new SqlParameter("#SurName", SqlDbType.VarChar)).Value = sSurname;
connection.Open();
int ID = command.ExecuteNonQuery();
connection.Close();
SQL aStoredProc
IF EXISTS(SELECT * FROM aTable WHERE ID = #ID)
-- User exists, update details
BEGIN
BEGIN TRAN
UPDATE aTable
SET
FirstName = #FirstName,
SurName = #SurName,
LastUpdate = GetDate()
WHERE ID = #ID
IF (##Error != 0)
ROLLBACK TRAN
ELSE
COMMIT TRAN
END
ELSE
-- New user
BEGIN
BEGIN TRAN
INSERT aTable (
FirstName,
SurName,
GetDate()
)
VALUES (
#FirstName,
#SurName,
#LastUpdate
)
SELECT #ID = ##IDENTITY
IF (##Error != 0)
ROLLBACK TRAN
ELSE
COMMIT TRAN
END
The parameter #ID is listed in the stored proc as:
#ID (int, Input/Output, No default)
and proc has 'Return integer'. This used to work fine with a VBA solution prior to a SQL Server 2005 upgrade.
Thanks in advance.
connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionInfo"]);
sql = "aStoredProc";
command = new SqlCommand(sql, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameter.Add(new SqlParameter("#FirstName", SqlDbType.VarChar)).Value = sFirstname;
command.Parameter.Add(new SqlParameter("#SurName", SqlDbType.VarChar)).Value = sSurname;
command.Parameter.Add(new SqlParameter("#SurName", SqlDbType.VarChar)).Value = sSurname;
SqlParameter ParamId = cmd.Parameters.Add( "#Id", SqlDbType.Int);
ParamId.Direction = ParameterDirection.InputOutput;
command.Parameter.Add(ParamId);
connection.Open();
command.ExecuteNonQuery();
int ID = ParamId.Value;
connection.Close();
you have to add output paramter in Parameter collection.
Read Value like above.
You have an error in your SQL, it should look like this:
INSERT aTable (FirstName,SurName,LastUpdate)
VALUES (#FirstName, #SurName, GetDate() )
Not like this:
INSERT aTable (
FirstName,
SurName,
GetDate()
)
VALUES (
#FirstName,
#SurName,
#LastUpdate
)
I am trying to insert a parameter through an aspx page via text box. I set my parameters up, but evertime I executenonquery, the #Username shows up in the database instead of the actual value.
Below is my code. Can anyone shed a little insight?
This is the full code:
protected void btn_SubmitUserInfo_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\Documents and Settings\\xm\\My Documents\\Visual Studio 2010\\Projects\\CreateUser\\CreateUser\\App_Data\\UserInformation.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True; Integrated Security=SSPI");
//Open the connection outside of the try statement
conn.Open();
try
{
//Create a command for the stored procedure and tie it into the connection
SqlCommand cmd = new SqlCommand("InsertUserValues", conn);
//Set the command type so it know to execute the stored proc
cmd.CommandType = CommandType.StoredProcedure;
//Declare Parameters
SqlParameter #UserID = new SqlParameter("#UserID", System.Data.SqlDbType.Int);
#UserID.Direction = ParameterDirection.Input;
#UserID.Value = txtUserID.Text;
SqlParameter #UserName = new SqlParameter("#UserName", System.Data.SqlDbType.VarChar);
#UserName.Direction = ParameterDirection.Input;
#UserName.Value = txtUserName.Text;
SqlParameter #UserPassword = new SqlParameter("#UserPassword", System.Data.SqlDbType.VarChar);
#UserPassword.Direction = ParameterDirection.Input;
#UserPassword.Value = txtPassword.Text;
SqlParameter #FirstName = new SqlParameter("#FirstName", System.Data.SqlDbType.VarChar);
#FirstName.Direction = ParameterDirection.Input;
#FirstName.Value = txtFirstName.Text;
SqlParameter #LastName = new SqlParameter("#LastName", System.Data.SqlDbType.VarChar);
#LastName.Direction = ParameterDirection.Input;
#LastName.Value = txtLastName.Text;
SqlParameter #Address = new SqlParameter("#Address", System.Data.SqlDbType.VarChar);
#Address.Direction = ParameterDirection.Input;
#Address.Value = txtAddress.Text;
SqlParameter #AptNum = new SqlParameter("#AptNum", System.Data.SqlDbType.VarChar);
#AptNum.Direction = ParameterDirection.Input;
#AptNum.Value = txtAptNumber.Text;
SqlParameter #City = new SqlParameter("#City", System.Data.SqlDbType.VarChar);
#City.Direction = ParameterDirection.Input;
#City.Value = txtCity.Text;
SqlParameter #State = new SqlParameter("#State", System.Data.SqlDbType.VarChar);
#State.Direction = ParameterDirection.Input;
#State.Value = txtState.Text;
//SqlParameter #Zip = new SqlParameter("#Zip", System.Data.SqlDbType.Int);
//#Zip.Direction = ParameterDirection.Input;
//#Zip.Value = Convert.ToInt32(txtZip.Text);
//add new parameter command to object
cmd.Parameters.Add(#UserID);
cmd.Parameters.Add(#UserName);
cmd.Parameters.Add(#UserPassword);
cmd.Parameters.Add(#FirstName);
cmd.Parameters.Add(#LastName);
cmd.Parameters.Add(#Address);
cmd.Parameters.Add(#AptNum);
cmd.Parameters.Add(#City);
cmd.Parameters.Add(#State);
//cmd.Parameters.Add(#Zip);
//execute nonquery
cmd.ExecuteNonQuery();
}
finally
{
lblSucess.Text = "Your information has been submitted";
//Close the connection
if (conn != null)
{
conn.Close();
}
}
This is the stored Procedure:
ALTER PROCEDURE dbo.InsertUserValues
#UserID int,
#UserName varchar(50),
#UserPassword varchar(100),
#FirstName varchar(50),
#LastName varchar(50),
#Address varchar(50),
#AptNum varchar(50),
#City varchar(50),
#State varchar(50)
AS
INSERT INTO tb_User( user_Name, password, f_Name, l_Name, address, apt_Number, city, state)
VALUES ( '#UserName', '#UserPassword', '#FirstName', '#LastName', '#Address', '#AptNum', '#City', '#State')
You have your parameter quoted in your SQL statement. Remove the single quotes from around the parameters in your stored procedure definition. Quoting them treats them as literal strings instead of parameters to be replaced.
ALTER PROCEDURE dbo.InsertUserValues
#UserID int,
#UserName varchar(50),
#UserPassword varchar(100),
#FirstName varchar(50),
#LastName varchar(50),
#Address varchar(50),
#AptNum varchar(50),
#City varchar(50),
#State varchar(50)
AS
INSERT INTO tb_User( user_Name, password, f_Name, l_Name, address, apt_Number, city, state)
VALUES (#UserName, #UserPassword, #FirstName, #LastName, #Address, #AptNum, #City, #State)
Your parameter name is not correct - you shouldn't use # in the beginning of C# variables. It should be:
SqlParameter UserName = new SqlParameter("#UserName", System.Data.SqlDbType.VarChar);
UserName.Direction = ParameterDirection.Input;
UserName.Value = txtUserName.Text;
cmd.Parameters.Add(UserName);
I don't think it's the root of your problem but that's just something I noticed.
We need more code to see what's the problem