Procedure or function Proc_PIP_Employee has too many arguments specified - c#

I am getting error
Procedure or function Proc_PIP_Employee has too many arguments specified
when trying to call procedure Proc_PIP_Employee from C# code. The count of parameters checked and those are same. Also datatypes are same. Even after that getting the same error.
C# code is
public int Add_Record(Employee emp)
{
try
{
if (con.State != ConnectionState.Open)
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
SqlParameter RETURN_VALUE_OUTPUT = new SqlParameter();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "dbo.Proc_PIP_Employee";
cmd.Parameters.Add("#Flag", SqlDbType.Int).Value = 1;
cmd.Parameters.Add("#Empid", SqlDbType.Int).Value = 0;
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = emp.Name ;
cmd.Parameters.Add("#Designation", SqlDbType.VarChar).Value = emp.Designation;
cmd.Parameters.Add("#Department", SqlDbType.VarChar).Value = emp.Department;
cmd.Parameters.Add("#DateofJoin", SqlDbType.DateTime).Value = emp.Dateofjoin;
cmd.Parameters.Add("#Phone", SqlDbType.VarChar).Value = emp.Phone;
cmd.Parameters.Add("#Isactive", SqlDbType.Int).Value = emp.IsActive;
cmd.Parameters.Add("#LoginUser", SqlDbType.NVarChar).Value = "admin";
RETURN_VALUE_OUTPUT = cmd.Parameters.Add("#ReturnId",SqlDbType.Int);
RETURN_VALUE_OUTPUT.Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
ReturnID = Convert.ToInt32(RETURN_VALUE_OUTPUT.Value.ToString());
}
}
catch (SqlException ex)
{
}
return ReturnID;
}
The stored procedure is:
ALTER PROCEDURE [dbo].[Proc_PIP_Employee]
#Flag int,
#Empid int,
#Name varchar(500),
#Designation varchar(200),
#Department varchar(200),
#DateofJoin datetime,
#Phone varchar(3000),
#Isactive int,
#LoginUser nvarchar(500)
AS
BEGIN
SET NOCOUNT ON ;
DECLARE #errorMessage VarChar(8000),
#errorSeverity Int,
#errorState Int,
#ReturnId Int,
#AlCode varchar(50),
#AlDesc varchar(1000),
#AlOp varchar(50),
#AlStatus varchar(50)
BEGIN TRY
BEGIN TRANSACTION
IF (#Flag = 1)
BEGIN
IF EXISTS (SELECT 1 FROM dbo.PIP_Employee
GROUP BY Name, Phone

You're adding an OUTPUT parameter for this stored procedure to your C# code - but there's no #ReturnId OUTPUT parameter in your stored procedure interface:
SqlParameter RETURN_VALUE_OUTPUT = new SqlParameter();
RETURN_VALUE_OUTPUT = cmd.Parameters.Add("#ReturnId",SqlDbType.Int);
RETURN_VALUE_OUTPUT.Direction = ParameterDirection.Output;
If you attempted to capture the return value - then use ParameterDirection.ReturnValue instead
SqlParameter RETURN_VALUE_OUTPUT = new SqlParameter();
RETURN_VALUE_OUTPUT = cmd.Parameters.Add("#ReturnId",SqlDbType.Int);
RETURN_VALUE_OUTPUT.Direction = ParameterDirection.ReturnValue;

Related

Insert into 2 tables with id from first

I have 2 tables
tbl_orgs:
tbl_orgs
and tbl_location_records:
tbl_location_records
I am using a stored procedure to insert data into these tables.
Insert Organization
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spInsOrg]
(#orgName nvarchar(50),
#orgCity nvarchar(50),
#orgArea nvarchar(50),
#orgTel nvarchar(50),
#orgEmail nvarchar(50),
#orgType nvarchar(50),
#orgStatus nvarchar(50),
#strOwner nvarchar(50),
#db_tstamp datetime2)
AS
SET NOCOUNT OFF;
INSERT INTO [tbl_orgs] ([orgName], [orgCity], [orgArea], [orgTel], [orgEmail], [orgType], [orgStatus], [strOwner], [db_tstamp])
VALUES (#orgName, #orgCity, #orgArea, #orgTel, #orgEmail, #orgType, #orgStatus, #strOwner, #db_tstamp);
SELECT
orgID, orgName, orgCity, orgArea, orgTel, orgEmail, orgType,
orgStatus, strOwner, db_tstamp
FROM
tbl_orgs
WHERE
(orgID = SCOPE_IDENTITY())
Insert Location Record
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spInsLoc]
(#userID int,
#orgID int,
#jobID int,
#strLat numeric(18, 0),
#strLong numeric(18, 0),
#strOwner varchar(50),
#db_tstamp datetime2)
AS
SET NOCOUNT OFF;
INSERT INTO [tbl_location_records] ([userID], [orgID], [jobID], [strLat], [strLong], [strOwner], [db_tstamp])
VALUES (#userID, #orgID, #jobID, #strLat, #strLong, #strOwner, #db_tstamp);
SELECT
recordID, userID, orgID, jobID, strLat, strLong, strOwner, db_tstamp
FROM
tbl_location_records
WHERE
(recordID = SCOPE_IDENTITY())
I want to use single form to add inserted organization's location record once organization record successfully inserted.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["IBS_3"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spInsOrg", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("orgName", SqlDbType.NVarChar).Value = txtOrgName.Text;
cmd.Parameters.Add("orgCity", SqlDbType.NVarChar).Value = txtCity.Text;
cmd.Parameters.Add("orgArea", SqlDbType.NVarChar).Value = txtArea.Text;
cmd.Parameters.Add("orgTel", SqlDbType.NVarChar).Value = txtTele.Text;
cmd.Parameters.Add("orgEmail", SqlDbType.NVarChar).Value = txtEmail.Text;
cmd.Parameters.Add("orgType", SqlDbType.NVarChar).Value = txtOrgType.Text;
cmd.Parameters.Add("orgStatus", SqlDbType.NVarChar).Value = txtStatus.Text;
cmd.Parameters.Add("#strOwner", SqlDbType.VarChar).Value = User.Identity.Name;
cmd.Parameters.Add("#db_tstamp", SqlDbType.DateTime2).Value = DateTime.Now;
conn.Open();
cmd.ExecuteNonQuery();
SqlCommand cmdloc = new SqlCommand("spInsLoc", conn);
cmdloc.CommandType = CommandType.StoredProcedure;
cmdloc.Parameters.Add("orgID", SqlDbType.Int).Value =
}
}
Trying to get some understanding from this link but I m clueless on this..
Inserting to one table, insert the ID to second table
Any help appreciated.
Thanks.
Add output parameter to the first stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spInsOrg]
(
#orgID int output,
#orgName nvarchar(50),
#orgCity nvarchar(50),
#orgArea nvarchar(50),
#orgTel nvarchar(50),
#orgEmail nvarchar(50),
#orgType nvarchar(50),
#orgStatus nvarchar(50),
#strOwner nvarchar(50),
#db_tstamp datetime2
)
AS
SET NOCOUNT OFF;
INSERT INTO [tbl_orgs] ([orgName], [orgCity], [orgArea], [orgTel], [orgEmail], [orgType], [orgStatus], [strOwner], [db_tstamp]) VALUES (#orgName, #orgCity, #orgArea, #orgTel, #orgEmail, #orgType, #orgStatus, #strOwner, #db_tstamp);
SELECT #orgID = SCOPE_IDENTITY()
add output param to command..
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spInsOrg", conn);
cmd.CommandType = CommandType.StoredProcedure;
var outParam = cmd.Parameters.Add("#orgID", SqlDbType.Int);
outParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add("#orgName", SqlDbType.NVarChar).Value = txtOrgName.Text;
cmd.Parameters.Add("#orgCity", SqlDbType.NVarChar).Value = txtCity.Text;
cmd.Parameters.Add("#orgArea", SqlDbType.NVarChar).Value = txtArea.Text;
cmd.Parameters.Add("#orgTel", SqlDbType.NVarChar).Value = txtTele.Text;
cmd.Parameters.Add("#orgEmail", SqlDbType.NVarChar).Value = txtEmail.Text;
cmd.Parameters.Add("#orgType", SqlDbType.NVarChar).Value = txtOrgType.Text;
cmd.Parameters.Add("#orgStatus", SqlDbType.NVarChar).Value = txtStatus.Text;
cmd.Parameters.Add("#strOwner", SqlDbType.VarChar).Value = User.Identity.Name;
cmd.Parameters.Add("#db_tstamp", SqlDbType.DateTime2).Value = DateTime.Now;
conn.Open();
cmd.ExecuteNonQuery();
var orgId = (int)outParam.Value;
SqlCommand cmdloc = new SqlCommand("spInsLoc", conn);
cmdloc.CommandType = CommandType.StoredProcedure;
}

How to fix error number: 8114 'Procedure or function has too many arguments specified' in c# windows application

I have to create procedure in SQLServer like,
create procedure LeaveMasterProcdure(
#code nvarchar(20),
#type nvarchar(20),
#condition nvarchar(1000),
#leavedays nvarchar(50)
)
As
DECLARE #Max INT
, #id varchar(50)
IF NOT EXISTS(SELECT id FROM LeaveMaster)
BEGIN
SET #id = 'L001'
INSERT INTO dbo.LeaveMaster(id,code,type,conditions,No_ofleaves)
VALUES(#id,#code,#type,#condition,#leavedays)
END
ELSE
BEGIN
SELECT #Max = CONVERT(INT, SUBSTRING(CONVERT(NVARCHAR(10),id), 2, 10)) FROM LeaveMaster
SET #id = 'L' + RIGHT('00' + CONVERT(NVARCHAR(10), #Max + 1), 5)
INSERT INTO dbo.LeaveMaster(id,code,type,conditions,No_ofleaves)
VALUES(#id,#code,#type,#condition,#leavedays)
END
Also I insert value by procedure is insert in SqlManagementStudio
But when I'm trying to insert a procedure by program I got Procedure or function has too many arguments specified exception. This code:
SqlCommand AddLeave = con.CreateCommand();
SqlParameter id = new SqlParameter("#id", SqlDbType.VarChar);
SqlParameter code = new SqlParameter("#code", SqlDbType.VarChar);
SqlParameter type = new SqlParameter("#type", SqlDbType.VarChar);
SqlParameter conditions = new SqlParameter("#conditions", SqlDbType.VarChar);
SqlParameter No_ofleaves = new SqlParameter("#No_ofleaves", SqlDbType.VarChar);
AddLeave.Parameters.Add(id);
AddLeave.Parameters.Add(code);
AddLeave.Parameters.Add(type);
AddLeave.Parameters.Add(conditions);
AddLeave.Parameters.Add(No_ofleaves);
SqlCommand ccc = new SqlCommand("select type from LeaveMaster", con);
SqlDataReader r1 = ccc.ExecuteReader();
while (r1.Read())
{
s1 = r1["type"].ToString();
}
if (s1 == null)
id.Value = " ";
else if (s1 != null)
id.Value = s1.ToString();
r1.Close();
code.Value = textBox_Leave_Code.Text;
type.Value = textBox_Leave_Type.Text;
conditions.Value = textBox_Conditions.Text;
No_ofleaves.Value = textBox_total_leave.Text;
AddLeave.Connection = con;
AddLeave.CommandText = "LeaveMasterProcdure #id,#code,#type,#conditions,#No_ofleaves";
try
{
AddLeave.ExecuteNonQuery();
MessageBox.Show("added");
}
catch (Exception vv)
{
MessageBox.Show(vv.ToString());
}
I don't know how to fix it. Please help me...
The #id parameter is not in the procedure.
#conditions in the code doesn't match #condition in the procedure.
#No_ofleaves doesn't match #leavedays in the procedure.
Here's an easy way to make these easier to catch. Copy the parameter list from the stored procedure into your C# code and comment it out. Now you've got them both in one place and you don't have to switch back and forth. When you're done delete the comments.
I usually copy and paste parameter names from my SQL because it eliminates the possibility of typos.
//#code nvarchar(20),
//#type nvarchar(20),
//#condition nvarchar(1000),
//#leavedays nvarchar(50)
SqlParameter id = new SqlParameter("#id", SqlDbType.VarChar);
SqlParameter code = new SqlParameter("#code", SqlDbType.VarChar);
SqlParameter type = new SqlParameter("#type", SqlDbType.VarChar);
SqlParameter conditions = new SqlParameter("#conditions", SqlDbType.VarChar);
SqlParameter No_ofleaves = new SqlParameter("#No_ofleaves", SqlDbType.VarChar);

SQL Update: Invalid object name 'master.dbo.TsqlSplit'

I have a really weird error. I am trying to run a stored procedure, that works perfectly on our production environment. Now, on our test server, I get the Invalid object name 'master.dbo.TsqlSplit'. error.
I have the code below, and it fails when it executes the scalar (and gives the invalid error).
bool res = false;
using (
var conn =
new SqlConnection(
ConfigurationManager.ConnectionStrings["VirksomhedsborsRestrictedAccess"].ConnectionString))
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "dbo.Saxis_UpdateCreateAdvert";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#AdvertId", SqlDbType.Int).Value = this.AdvertID;
//this.ActivatedDate;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar, 200).Value = this.Address.NullToDbNull();
cmd.Parameters.Add("#AdvertLevel", SqlDbType.Int).Value = this.AdvertLevel.NullToDbNull();
cmd.Parameters.Add("#AdvertType", SqlDbType.NVarChar, 200).Value = this.AdvertTypeRaw.NullToDbNull();
cmd.Parameters.Add("#BusinessEntityType", SqlDbType.Int).Value = this.BusinessEntityType.NullToDbNull();
cmd.Parameters.Add("#CanMove", SqlDbType.Bit).Value = this.CanMove.NullToDbNull();
cmd.Parameters.Add("#City", SqlDbType.NVarChar, 200).Value = this.City.NullToDbNull();
cmd.Parameters.Add("#CompanyName", SqlDbType.NVarChar, 200).Value = this.CompanyName.NullToDbNull();
cmd.Parameters.Add("#Competition", SqlDbType.NText).Value = this.Competition.Value.NullToDbNull();
cmd.Parameters.Add("#ContactEmail", SqlDbType.NVarChar, 200).Value = this.ContactEmail.NullToDbNull();
cmd.Parameters.Add("#ContactName", SqlDbType.NVarChar, 200).Value = this.ContactName.NullToDbNull();
cmd.Parameters.Add("#ContactTelephone", SqlDbType.NVarChar, 200).Value = this.ContactTelephone.NullToDbNull();
//this.CreatedDate;
cmd.Parameters.Add("#Description", SqlDbType.NText).Value = this.Description.Value.NullToDbNull();
cmd.Parameters.Add("#Employees", SqlDbType.Int).Value = this.Employees.HasValue ? (int)this.Employees.Value : (object)DBNull.Value;
cmd.Parameters.Add("#ExpiryDate", SqlDbType.DateTime).Value = this.ExpiryDate.NullToDbNull(); // Expiry date extended package
cmd.Parameters.Add("#FinancingBySeller", SqlDbType.Bit).Value = this.FinancingBySeller.NullToDbNull();
cmd.Parameters.Add("#FinancingInterest", SqlDbType.Float).Value = this.FinancingInterest.NullToDbNull();
cmd.Parameters.Add("#FinancingMonths", SqlDbType.Int).Value = this.FinancingMonths.NullToDbNull();
cmd.Parameters.Add("#FinancingPayout", SqlDbType.BigInt).Value = this.FinancingPayout.NullToDbNull();
cmd.Parameters.Add("#FoundedYear", SqlDbType.Int).Value = this.FoundedYear.NullToDbNull();
cmd.Parameters.Add("#FurnitureIncluded", SqlDbType.Bit).Value = (this.Furniture == null ? DBNull.Value : this.Furniture.IsIncluded.NullToDbNull());
cmd.Parameters.Add("#FurnitureValue", SqlDbType.BigInt).Value = (this.Furniture == null ? DBNull.Value : this.Furniture.Value.NullToDbNull());
cmd.Parameters.Add("#IdealPartner", SqlDbType.NText).Value = this.IdealPartner.Value.NullToDbNull();
cmd.Parameters.Add("#OperationType", SqlDbType.Int).Value = (int)this.OperationType;
// Must have room for 9 images. Filenames are GUID + .ext + separator
cmd.Parameters.Add("#Images", SqlDbType.NVarChar, 400).Value = this.Images != null ? string.Join(",", this.Images.ConvertAll(f => f.Filename).ToArray()) : "";
cmd.Parameters.Add("#OnlyVIPContact", SqlDbType.Bit).Value = this.OnlyVIPContact.NullToDbNull();
cmd.Parameters.Add("#Price", SqlDbType.Int).Value = this.Price.NullToDbNull();
cmd.Parameters.Add("#PrimaryRegion", SqlDbType.Int).Value = this.PrimaryRegion.Id.NullToDbNull();
cmd.Parameters.Add("#PrimarySector", SqlDbType.Int).Value = this.PrimarySector.Id.NullToDbNull();
cmd.Parameters.Add("#ProfitBeforeTaxes", SqlDbType.BigInt).Value = this.ProfitBeforeTaxes.NullToDbNull();
cmd.Parameters.Add("#RealEstateIncluded", SqlDbType.Bit).Value = this.RealEstate == null ? DBNull.Value : this.RealEstate.IsIncluded.NullToDbNull();
cmd.Parameters.Add("#RealEstateValue", SqlDbType.BigInt).Value = this.RealEstate == null ? DBNull.Value : this.RealEstate.Value.NullToDbNull();
cmd.Parameters.Add("#ReasonForSale", SqlDbType.Int).Value = this.ReasonForSale.NullToDbNull();
cmd.Parameters.Add("#Regions", SqlDbType.NVarChar, 400).Value = this.Regions != null ? string.Join(",", this.Regions.ConvertAll(r => r.Id.ToString()).ToArray()) : "";
cmd.Parameters.Add("#RevenuePrediction", SqlDbType.Int).Value = this.RevenuePrediction.NullToDbNull();
cmd.Parameters.Add("#RevenueStatus", SqlDbType.Int).Value = this.RevenueStatus.NullToDbNull();
cmd.Parameters.Add("#SearchTerms", SqlDbType.NVarChar, 200).Value = this.SearchTerms != null ? string.Join(",", this.SearchTerms.ToArray()) : "";
cmd.Parameters.Add("#Sectors", SqlDbType.NVarChar, 400).Value = this.Sectors != null ? string.Join(",", this.Sectors.ConvertAll(s => s.Id.ToString()).ToArray()) : "";
if (this.AdvertLevel == AdvertLevel.Regular
&& (this.Status == AdvertStatus.Enabled
|| this.Status == AdvertStatus.ApprovedNotPublished
|| this.AdvertID == -1))
this.Status = AdvertStatus.PendingApproval;
cmd.Parameters.Add("#Status", SqlDbType.Int).Value = this.Status.NullToDbNull();
cmd.Parameters.Add("#StockIncluded", SqlDbType.Bit).Value = this.Stock == null ? DBNull.Value : this.Stock.IsIncluded.NullToDbNull();
cmd.Parameters.Add("#StockValue", SqlDbType.BigInt).Value = this.Stock == null ? DBNull.Value : this.Stock.Value.NullToDbNull();
cmd.Parameters.Add("#Subtitle", SqlDbType.NVarChar, 200).Value = this.Subtitle.NullToDbNull();
cmd.Parameters.Add("#Training", SqlDbType.NText).Value = this.Training.Value.NullToDbNull();
cmd.Parameters.Add("#TransactionType", SqlDbType.Int).Value = this.TransactionType.NullToDbNull();
cmd.Parameters.Add("#Turnover", SqlDbType.Int).Value = this.Turnover.NullToDbNull();
cmd.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = this.UserID.NullToDbNull();
cmd.Parameters.Add("#VATnumber", SqlDbType.NVarChar, 200).Value = this.VATNumber.NullToDbNull();
cmd.Parameters.Add("#ZipCode", SqlDbType.NVarChar, 50).Value = this.ZipCode.NullToDbNull();
cmd.Parameters.Add("#CompanyCountry", SqlDbType.VarChar, 3).Value = this.CompanyCountry.NullToDbNull();
cmd.Parameters.Add("#CompanyZip", SqlDbType.NVarChar, 25).Value = this.CompanyZip.NullToDbNull();
int id = (int) cmd.ExecuteScalar();
if (this.AdvertID == -1) this.AdvertID = id;
res = (this.AdvertID == id);
conn.Close();
}
My stored procedure is really simple, and looks like this:
USE [Virksomhedsbors]
GO
/****** Object: StoredProcedure [dbo].[Saxis_UpdateCreateAdvert] Script Date: 10-09-2014 10:03:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Saxis_UpdateCreateAdvert]
#AdvertID INT,
#Address NVARCHAR(200),
#AdvertLevel INT,
#AdvertType NVARCHAR(200),
#BusinessEntityType INT,
#CanMove BIT,
#City NVARCHAR(200),
#CompanyName NVARCHAR(200),
#Competition NTEXT,
#ContactEmail NVARCHAR(200),
#ContactName NVARCHAR(200),
#ContactTelephone NVARCHAR(200),
#Description NTEXT,
#Employees INT,
#ExpiryDate DATETIME,
#FinancingBySeller BIT,
#FinancingInterest FLOAT,
#FinancingMonths INT,
#FinancingPayout BIGINT,
#FoundedYear INT,
#FurnitureIncluded BIT,
#FurnitureValue BIGINT,
#IdealPartner NTEXT,
#Images NVARCHAR(400),
#OnlyVIPContact BIT,
#Price INT,
#PrimaryRegion INT,
#PrimarySector INT,
#ProfitBeforeTaxes BIGINT,
#RealEstateIncluded BIT,
#RealEstateValue BIGINT,
#ReasonForSale INT,
#Regions NVARCHAR(400),
#RevenuePrediction INT,
#RevenueStatus INT,
#SearchTerms NVARCHAR(200),
#Sectors NVARCHAR(400),
#Status INT,
#StockIncluded BIT,
#StockValue BIGINT,
#Subtitle NVARCHAR(200),
#Training NTEXT,
#TransactionType INT,
#Turnover INT,
#UserID UNIQUEIDENTIFIER,
#VATNumber NVARCHAR(200),
#ZipCode NVARCHAR(50),
#CompanyCountry VARCHAR(3) = NULL,
#CompanyZip NVARCHAR(25) = NULL,
#OperationType INT = NULL
AS
IF #AdvertId = -1
BEGIN
-- CREATE if #AdvertId is -1
DECLARE #now DATETIME
SET #now = GETDATE()
DECLARE #EV BIT
SET #EV = 0
BEGIN TRANSACTION
SELECT #EV = EmailVerified
FROM [User]
WHERE MembershipId=#UserId
SET #EV = ISNULL(#EV, 0)
INSERT INTO Advert (
CreatedDate,
ModifiedDate,
EmailVerified,
EmailVerificationGuid,
Address,
AdvertLevel,
AdvertType,
BusinessEntityTypeID,
CanMove,
City,
CompanyName,
DescCompetition,
ContactEmail,
ContactName,
ContactTelephone,
Description,
Employees,
ExpiryDate,
FinancingBySeller,
FinancingInterest,
FinancingMonths,
FinancingPayout,
FoundedYear,
FurnitureIncluded,
FurnitureValue,
DescIdealPartner,
OnlyVIPContact,
Price,
Region,
Sector,
ProfitBeforeTaxes,
RealEstateIncluded,
RealEstateValue,
ReasonForSale,
RevenuePrediction,
RevenueStatus,
SearchTerms,
Status,
StockIncluded,
StockValue,
Subtitle,
DescTraining,
TransactionType,
Turnover,
UserID,
CVR,
ZipCode,
CompanyCountry,
CompanyZip,
OperationType
)
VALUES
(
#now,
#now,
#EV,
NEWID(),
#Address,
#AdvertLevel,
#AdvertType,
#BusinessEntityType,
#CanMove,
#City,
#CompanyName,
#Competition,
#ContactEmail,
#ContactName,
#ContactTelephone,
#Description,
#Employees,
#ExpiryDate,
#FinancingBySeller,
#FinancingInterest,
#FinancingMonths,
#FinancingPayout,
#FoundedYear,
#FurnitureIncluded,
#FurnitureValue,
#IdealPartner,
#OnlyVIPContact,
#Price,
#PrimaryRegion,
#PrimarySector,
#ProfitBeforeTaxes,
#RealEstateIncluded,
#RealEstateValue,
#ReasonForSale,
#RevenuePrediction,
#RevenueStatus,
#SearchTerms,
#Status,
#StockIncluded,
#StockValue,
#Subtitle,
#Training,
#TransactionType,
#Turnover,
#UserID,
#VATNumber,
#ZipCode,
#CompanyCountry,
#CompanyZip,
#OperationType
)
IF ##ROWCOUNT > 0
BEGIN
--SET #AdvertID = SCOPE_IDENTITY() -- is scope_identity f*cked? -- maybe because of the trigger
SELECT TOP 1 #AdvertID = AdvertID FROM Advert WHERE CreatedDate=#now AND UserID=#UserID AND AdvertLevel = #AdvertLevel
ORDER BY AdvertID DESC
END
COMMIT TRANSACTION
END
ELSE
BEGIN
-- UPDATE
SELECT #EV = EmailVerified
FROM [User]
WHERE MembershipId=#UserId
SET #EV = ISNULL(#EV, 0)
UPDATE Advert
SET
ModifiedDate=GETDATE(),
Address=#Address,
AdvertLevel=#AdvertLevel,
AdvertType=#AdvertType,
BusinessEntityTypeID=#BusinessEntityType,
CanMove=#CanMove,
City=#City,
CompanyName=#CompanyName,
DescCompetition=#Competition,
ContactEmail=#ContactEmail,
ContactName=#ContactName,
ContactTelephone=#ContactTelephone,
Description=#Description,
Employees=#Employees,
ExpiryDate=#ExpiryDate,
FinancingBySeller=#FinancingBySeller,
FinancingInterest=#FinancingInterest,
FinancingMonths=#FinancingMonths,
FinancingPayout=#FinancingPayout,
FoundedYear=#FoundedYear,
FurnitureIncluded=#FurnitureIncluded,
FurnitureValue=#FurnitureValue,
DescIdealPartner=#IdealPartner,
OnlyVIPContact=#OnlyVIPContact,
Price=#Price,
Region=#PrimaryRegion,
Sector=#PrimarySector,
ProfitBeforeTaxes=#ProfitBeforeTaxes,
RealEstateIncluded=#RealEstateIncluded,
RealEstateValue=#RealEstateValue,
ReasonForSale=#ReasonForSale,
RevenuePrediction=#RevenuePrediction,
RevenueStatus=#RevenueStatus,
SearchTerms=#SearchTerms,
Status=#Status,
StockIncluded=#StockIncluded,
StockValue=#StockValue,
Subtitle=#Subtitle,
DescTraining=#Training,
TransactionType=#TransactionType,
Turnover=#Turnover,
CVR=#VATNumber,
ZipCode=#ZipCode,
UserID=#UserID, -- Allow the Anonymous User ID to be changed
CompanyCountry = #CompanyCountry,
CompanyZip = #CompanyZip,
EmailVerified = #EV,
OperationType = #OperationType
WHERE
AdvertID = #AdvertID
--AND UserID=#UserID -- Only accept the change the advert if user id is the same
END
IF (ISNULL(#AdvertID, -1) <> -1)
BEGIN
BEGIN TRANSACTION
DELETE FROM AdvertRegion
WHERE AdvertID = #AdvertID
INSERT INTO AdvertRegion (AdvertID, RegionID)
SELECT #AdvertID, Item
FROM master.dbo.TsqlSplit(#Regions)
COMMIT TRANSACTION
BEGIN TRANSACTION
DELETE FROM AdvertSector
WHERE AdvertID = #AdvertID
INSERT INTO AdvertSector (AdvertID, SectorID)
SELECT #AdvertId, Item
FROM master.dbo.TsqlSplit(#Sectors)
COMMIT TRANSACTION
BEGIN TRANSACTION
DELETE FROM AdImages
WHERE AdvertID = #AdvertID
INSERT INTO AdImages (AdvertID, FileName)
SELECT #AdvertId, Item
FROM master.dbo.TsqlSplit(#Images)
COMMIT TRANSACTION
END
SELECT #AdvertID
Any idea what the master.dbo.TsqlSplit error could be?
In this part of the StoredProcedure (and also after that point) you use the TSqlSplit object.
BEGIN TRANSACTION
DELETE FROM AdvertRegion
WHERE AdvertID = #AdvertID
INSERT INTO AdvertRegion (AdvertID, RegionID)
SELECT #AdvertID, Item
FROM master.dbo.TsqlSplit(#Regions)
COMMIT TRANSACTION
I suppose, from its name, that it is a function that splits the parameters #Regions, #Images and #Sectors and returns a table used to insert new records in the AdvertRegion, AdvertSector and AdImages tables. You mentioned also that this code works without problems in your production server but not in your test server. So, the only possible reason of the error is the fact that this function is missing in your test server.

Get Return Value from Stored procedure in asp.net

i have a stored procedure
ALTER PROC TESTLOGIN
#UserName varchar(50),
#password varchar(50)
As
Begin
declare #return int;
set #return = (SELECT COUNT(*)
FROM CPUser
WHERE UserName = #UserName
AND Password = #password);
return #return;
End
and in c#
SqlConnection con = db.con;
SqlCommand cmd = new SqlCommand("TESTLOGIN", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parm = new SqlParameter("#return", SqlDbType.Int);
parm.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(parm);
cmd.Parameters.Add(new SqlParameter("#UserName", txtUserName.Text.ToString().Trim()));
cmd.Parameters.Add(new SqlParameter("#password", txtPassword.Text.ToString().Trim()));
cmd.ExecuteNonQuery();
con.Close();
int id = Convert.ToInt32(parm.Value);
but it always return 0. Please help me to solve this problem
You need a parameter with Direction set to ParameterDirection.ReturnValue in code but no need to add an extra parameter in SP. Try this
SqlParameter returnParameter = cmd.Parameters.Add("RetVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int id = (int) returnParameter.Value;
2 things.
The query has to complete on sql server before the return value is sent.
The results have to be captured and then finish executing before
the return value gets to the object.
In English, finish the work and then retrieve the value.
this will not work:
cmm.ExecuteReader();
int i = (int) cmm.Parameters["#RETURN_VALUE"].Value;
This will work:
SqlDataReader reader = cmm.ExecuteReader();
reader.Close();
foreach (SqlParameter prm in cmd.Parameters)
{
Debug.WriteLine("");
Debug.WriteLine("Name " + prm.ParameterName);
Debug.WriteLine("Type " + prm.SqlDbType.ToString());
Debug.WriteLine("Size " + prm.Size.ToString());
Debug.WriteLine("Direction " + prm.Direction.ToString());
Debug.WriteLine("Value " + prm.Value);
}
if you are not sure
check the value of the parameter
before during and after the results have been processed by the reader.
you can try this.Add the parameter as output direction and after executing the query get the output parameter value.
SqlParameter parmOUT = new SqlParameter("#return", SqlDbType.Int);
parmOUT.Direction = ParameterDirection.Output;
cmd.Parameters.Add(parmOUT);
cmd.ExecuteNonQuery();
int returnVALUE = (int)cmd.Parameters["#return"].Value;
Procedure never returns a value.You have to use a output parameter in store procedure.
ALTER PROC TESTLOGIN
#UserName varchar(50),
#password varchar(50)
#retvalue int output
as
Begin
declare #return int
set #return = (Select COUNT(*)
FROM CPUser
WHERE UserName = #UserName AND Password = #password)
set #retvalue=#return
End
Then you have to add a sqlparameter from c# whose parameter direction is out.
Hope this make sense.
If you want to to know how to return a value from stored procedure to Visual Basic.NET. Please read this tutorial: How to return a value from stored procedure
I used the following stored procedure to return the value.
CREATE PROCEDURE usp_get_count
AS
BEGIN
DECLARE #VALUE int;
SET #VALUE=(SELECT COUNT(*) FROM tblCar);
RETURN #VALUE;
END
GO
Do it this way (make necessary changes in code)..
SqlConnection con = new SqlConnection(GetConnectionString());
con.Open();
SqlCommand cmd = new SqlCommand("CheckUser", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("username", username.Text);
SqlParameter p2 = new SqlParameter("password", password.Text);
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
SqlDataReader rd = cmd.ExecuteReader();
if(rd.HasRows)
{
//do the things
}
else
{
lblinfo.Text = "abc";
}

Why a SqlParameter does not get value?

I am trying to initialize the value of a SqlParameter with a string. but why does it not get the value ?
This is what I tried:
int loadChart(string status)
{
connect();
SqlParameter[] parameters ={
new SqlParameter("status", SqlDbType.VarChar, 10),
new SqlParameter("count", SqlDbType.Int, 4)
};
parameters[0].Value = status;
parameters[1].Direction = ParameterDirection.Output;
SqlCommand cmd = new SqlCommand("sp_Arsenic_getSourceStatusCount", objConnection);
foreach (SqlParameter param in parameters)
{
cmd.Parameters.Add(param);
}
cmd.ExecuteNonQuery();
disConnect();
int count;
count =(int) parameters[1].Value;
return count;
}
}
The stored procedure:
alter procedure sp_Arsenic_getSourceStatusCount
#status varchar(10),
#count int
as
select #count=COUNT(status) from Arsenic_WaterSource where status=#status
return 1
Inserting a breakpoint I have discovered that the string variable status gets its value "safe" but at parameters[0].Value = (string) status; line parameters[0].value gets null. How to resolve this issue ?
You did not define your #count parameter as an OUTPUT parameter in your procedure:
alter procedure sp_Arsenic_getSourceStatusCount
#status varchar(10),
#count int OUTPUT /* <-------------- */
as
select #count=COUNT(status) from Arsenic_WaterSource where status=#status
return 1
Try this:
connect();
SqlCommand cmd = new SqlCommand("sp_Arsenic_getSourceStatusCount", objConnection);
cmd.Parameters.Add(new SqlParameter("#status", status));
SqlParameter pCount = new SqlParameter("#count", 0);
pCount.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(pCount);
cmd.ExecuteNonQuery();
disConnect();
int count = Convert.ToInt32(parameters[1].Value);
return count;
And this:
alter procedure sp_Arsenic_getSourceStatusCount
#status varchar(10),
#count int = 0 OUTPUT
as
set nocount on
select #count=COUNT(status) from Arsenic_WaterSource where status=#status
go

Categories