C# SQL output code issue - c#

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

Related

How to return Identity Column from SQL Server procedure in C# code

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

Procedure or function expects parameter , which was not supplied

Procedure or function 'login' expects parameter '#Abc', which was not supplied
4 hours searching and trying and no use I already supplied this parameter (copy/paste) and the number of parameters given to procedure is the same of procedure and in order.
#Abc is an output parameter.
Stored procedure definition:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[login]
(
#Abc int output,
#firstname varchar(255) output,
#lastname varchar(255) output,
#Email varchar(255),
#pass varchar(255)
)
As
begin
if not exists (select Email from user_1 where email=#email)
select #Abc = 0
else begin
if not exists (
select Email from user_1 where email =#Email and password = #pass
)
select #Abc = 1
else
select #Abc = 2,#firstname = u.first_name ,#lastname=u.last_name from user_1 u where u.email = #email
end
end
Code to call the stored procedure:
myCon.Open();
TextBox username = UserName;
TextBox password = Password;
SqlCommand myCommand = new SqlCommand("login", myCon);
SqlParameter count= myCommand.Parameters.Add("#Abc", SqlDbType.Int);
count.Direction = ParameterDirection.Output;
SqlParameter fnp = myCommand.Parameters.Add("#firstname", SqlDbType.VarChar,255);
fnp.Direction = ParameterDirection.Output;
SqlParameter lnp = myCommand.Parameters.Add("#lastname", SqlDbType.VarChar, 255);
lnp.Direction = ParameterDirection.Output;
myCommand.Parameters.AddWithValue("#Email",username.Text);
myCommand.Parameters.AddWithValue("#pass", password.Text);
myCommand.ExecuteNonQuery();
myCon.Close();
You have omitted:
myCommand.CommandType = CommandType.StoredProcedure;
So the command sent to the DB is a malfed sp_executeSQL call instead of the desired exec login
FYI there is also a shorter syntax:
myCommand.Parameters.Add("#Abc", SqlDbType.Int).Direction = ParameterDirection.Output;

No value was supplied, to Output Parameter

I am getting error as "Procedure or function 'Artical_i' expects parameter '#ID', which was not supplied.". But my #ID parameter is Output parameter.
-------------------------------c# Code----------------------------------------
int retVal=0;
SqlParameter outputParam = new SqlParameter();
outputParam.ParameterName = "#ID";
outputParam.SqlDbType = SqlDbType.Int;
outputParam.Direction = ParameterDirection.Output;
outputParam.Value = retVal; /// Added in Edit
SqlParameter[] sParam =
{
outputParam,
new SqlParameter("#Title",this.Title),
new SqlParameter("#BaseUri",this.BaseUri),
new SqlParameter("#Description",this.Description),
new SqlParameter("#ShortDescription",this.ShortDescription),
new SqlParameter("#Copyright",this.Copyright),
new SqlParameter("#ItemID",this.ItemID),
new SqlParameter("#LastUpdatedTime",this.LastUpdatedTime),
new SqlParameter("#PublishDate",this.PublishDate),
new SqlParameter("#SourceFeedURL",this.SourceFeedURL)
};
SqlConnection connection = new SqlConnection(connectionString)
SqlCommand command = new SqlCommand();
connection.Open();
command.Connection = connection;
command.CommandText = procedureName;
command.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter p in sParam )
{
command.Parameters.AddWithValue(p.ParameterName, p.Value);
}
command.ExecuteNonQuery(); /// Error Here as "Procedure or function 'Artical_i' expects parameter '#ID', which was not supplied."
retVal = Convert.ToInt32(outputParam.Value); // Value returned as 0 here
-------------------- Stored Procedure---------------------------
IF OBJECT_ID (N'Artical_i', N'P') IS NOT NULL
Begin
drop procedure Artical_i
End
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Procedure Artical_i
(
#Title nvarchar(500),
#BaseUri nvarchar(2083),
#Description nvarchar(max),
#ShortDescription nvarchar(500),
#Copyright nvarchar(250),
#ItemID varchar(250),
#LastUpdatedTime datetimeoffset(7),
#PublishDate datetimeoffset(7),
#SourceFeedURL nvarchar(2083),
#ID int OUTPUT
)
as
Begin
BEGIN TRY
BEGIN TRANSACTION
set nocount on;
INSERT INTO [dbo].[Artical]
([Title]
,[BaseUri]
,[Description]
,[ShortDescription]
,[Copyright]
,[ItemID]
,[LastUpdatedTime]
,[PublishDate]
,[CreatedDate]
,[SourceFeedURL])
VALUES
(#Title,
#BaseUri,
#Description,
#ShortDescription,
#Copyright,
#ItemID,
#LastUpdatedTime,
#PublishDate,
Getdate(),
#SourceFeedURL)
Select #ID =SCOPE_IDENTITY()
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
Select #ID =0
END CATCH
End
GO

how to pass ref variable to a SQL stored Procedure using ADO.NET?

i have that code using LINQ to call a stored procedure to save some data into database then return two variables from the stored procedure.
[ASP.NET code]
dbDataContext dbo = new dbDataContext();
dbo.AddNewDoctor(doctorName, email, password, ref DocId, ref result);
[SQL]
create PROCEDURE [dbo].[AddNewDoctor]
#doctorname nvarchar(100),
#email nvarchar(100),
#password nvarchar(MAX),
#docId int out,
#Result int out
AS
BEGIN
SET NOCOUNT ON;
declare #idCounter int
select #idCounter = count(*) from dbo.doctors
if EXISTS (select * from dbo.doctors where e_mail = #email)
begin
SET #Result = -1
set #docId= 0
end
else
begin
INSERT INTO [dbo].[doctors]
([doctor_id]
,[doctorname]
,[e_mail]
,[password]
VALUES
((#idCounter +1)
,#docotorname
,#email
,#password
)
SET #Result = 1
set #docId= (#idCounter + 1)
end
END
this code work very well what i want to do now to use ADO instead of LINQ, the problem with me is that i can't pass the ref variable as in LINQ so how can i do it using ADO
You'll have to do something like this. Use ParameterDirection
SqlParameter output = new SqlParameter(paramName, dbType);
output.Direction = ParameterDirection.Output;
command.Parameters.Add(output);
In your case you've to use SqlDbType.Int. Use Value property to read return value.
SqlParameter output = new SqlParameter(paramName, SqlDbType.Int);
output.Direction = ParameterDirection.Output;
command.Parameters.Add(output);
int Result = (int) output.Value; or int? Result = (int?) output.Value;
Try this
using (SqlConnection con = new SqlConnection("Your connection string"))
{
con.Open();
SqlCommand mycommand = new SqlCommand();
mycommand.Connection = con;
mycommand.CommandText = "dbo.AddNewDoctor";
mycommand.CommandType = CommandType.StoredProcedure;
mycommand.Parameters.AddWithValue(doctorName);
mycommand.Parameters.AddWithValue(email);
mycommand.Parameters.AddWithValue(password);
mycommand.Parameters.AddWithValue(ref DocId);
mycommand.Parameters.AddWithValue(ref result);
mycommand.ExecuteNonQuery();
}
Hope this helps thanks.
Refer to this article, there is an working example:
http://csharp-guide.blogspot.de/2012/05/linq-to-sql-call-stored-procedure-with_25.html

Stored procedure error when use computed column for ID

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

Categories

Resources