I ran into a problem for which I couldn't find a solution in existing similarly asked questions. The problem is that I have the following stored procedure:
ALTER PROCEDURE SP_EditCustomer #ID int, #Name NVarchar(100), #Email Nvarchar(200), #Contact bigint,
#Address NVarchar(350), #About NVarChar(350), #Image image = null
AS
if(#Image is null)
Begin
UPDATE clientTable
SET ClientName = #Name, Contact= #Contact, Address = #Address, About = #About, Email = #Email
WHERE ClientID = #ID;
End
Else
Begin
UPDATE clientTable
SET ClientName = #Name, Contact= #Contact, Address = #Address, About = #About, Email = #Email,
Photo = #Image
WHERE ClientID = #ID;
End
I have set the #image parameter to be null as default but whenever I connect to SQL Server with the following code in C# winforms:
// Inserting image into DB
byte[] img = null;
if (imgLoc != null && imgLoc != "")
{
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
}
else
{
img = null;
}
//Connecting to Database
cmd = conString.CreateCommand();
cmd.CommandText = "Exec SP_EditCustomer #ID, #Name, #Email, #Contact, #Address, #About, #Image";
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(txtEditByID.Text);
cmd.Parameters.Add("#Name", SqlDbType.NVarChar, 100).Value = txtFullName.Text.ToString();
cmd.Parameters.Add("#Email", SqlDbType.NVarChar, 200).Value = txtEmail.Text.ToString();
cmd.Parameters.Add("#Contact", SqlDbType.BigInt).Value = txtContact.Text;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar, 350).Value = txtAddress.Text.ToString();
cmd.Parameters.Add("#About", SqlDbType.NVarChar, 350).Value = txtAbout.Text.ToString();
cmd.Parameters.Add("#Image", SqlDbType.Image).Value = img;
conString.Open();
cmd.ExecuteNonQuery();
conString.Close();
I get this error:
The parameterized query '(#ID int,#Name nvarchar(100),#Email nvarchar(200),#Contact bigin' expects the parameter '#Image', which was not supplied.
Although if no new image is selected then the existing image shouldn't change (and for this purpose I have passed null but still I get the error above).
Thanks to #DaleK for suggesting the DBNull.Value.
I have solved it with his suggestion by adding the following lines:
if(img!=null)
cmd.Parameters.Add("#Image", SqlDbType.Image).Value = img;
else
cmd.Parameters.Add("#Image", SqlDbType.Image).Value = DBNull.Value;
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;
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.
I want to know what (if any) is wrong with the below stored procedure for updating address:
I have also given my database image to get a clear idea....
ALTER PROCEDURE [dbo].[usp_UpdateAddress]
(#OriginalEmail nvarchar(50), #FirstName varchar(50), #LastName varchar(50),
#Country_ID int, #AddressLine1 varchar(50), #AddressLine2 varchar(50),
#AddressLine3 varchar(50), #Telephone varchar(50), #Email nvarchar(50),
#City varchar(50), #State_ID int, #PostalCode varchar(50), #Mobile varchar(50))
AS
BEGIN
DECLARE #User_ID INT
SELECT #User_ID = ID FROM AUser Where Email = #OriginalEmail
UPDATE [AUserAddress]
SET [AUser_ID] = #User_ID, [FirstName] = #FirstName, [LastName] = #LastName,
[Country_ID] = #Country_ID, [AddressLine1] = #AddressLine1,
[AddressLine2] = #AddressLine2, [AddressLine3] = #AddressLine3,
[Telephone] = #Telephone, [Email] = #Email, [City] = #City,
[State_ID] = #State_ID, [PostalCode] = #PostalCode, [Mobile] = #Mobile
WHERE
Email = #OriginalEmail
END
Called from C#:
private void UpdateAddress()
{
try
{
string strSession = objGetSession.GetEmailFromSession();
con.Open();
SqlCommand sqlCmd = new SqlCommand("usp_UpdateAddress", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("#OriginalEmail ", SqlDbType.NVarChar, 50).Value = strSession;
sqlCmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 50).Value = txtFirstName.Text;
sqlCmd.Parameters.Add("#LastName", SqlDbType.VarChar, 50).Value = txtLastName.Text;
sqlCmd.Parameters.Add("#AddressLine1", SqlDbType.VarChar, 50).Value = txtAddressLine1.Text;
sqlCmd.Parameters.Add("#AddressLine2", SqlDbType.VarChar, 50).Value = txtAddressLine2.Text;
sqlCmd.Parameters.Add("#AddressLine3", SqlDbType.VarChar, 50).Value = txtAddressLine3.Text;
sqlCmd.Parameters.Add("#Telephone", SqlDbType.VarChar, 50).Value = txtTelephone.Text;
sqlCmd.Parameters.Add("#Email", SqlDbType.NVarChar, 50).Value = txtEmailAddress.Text;
sqlCmd.Parameters.Add("#Country_ID", SqlDbType.Int).Value = ddlCountry.SelectedItem.Value;
sqlCmd.Parameters.Add("#City", SqlDbType.VarChar, 50).Value = txtCity.Text;
sqlCmd.Parameters.Add("#State_ID", SqlDbType.Int).Value = ddlState.SelectedValue.ToString();
sqlCmd.Parameters.Add("#PostalCode", SqlDbType.VarChar, 50).Value = txtPostalCode.Text;
sqlCmd.Parameters.Add("#Mobile", SqlDbType.VarChar, 50).Value = txtMobile.Text;
sqlCmd.Connection = con;
sqlCmd.ExecuteNonQuery();
con.Close();
mpeTest.Show();
Response.Write("<script> alert('Address Updated!') </script>");
}
catch (Exception e)
{
Response.Write("An Error Occurred" + e);
}
}
Is the stored procedure not executing? Debugging shows that in Update Address() it does take the new value but when execution is completed, the database is not updated...
What if you UPDATE it directly by joining the tables?
UPDATE a
SET a.[auser_id] = b.ID,
a.[firstname] = #FirstName,
a.[lastname] = #LastName,
a.[country_id] = #Country_ID,
a.[addressline1] = #AddressLine1,
a.[addressline2] = #AddressLine2,
a.[addressline3] = #AddressLine3,
a.[telephone] = #Telephone,
a.[email] = #Email,
a.[city] = #City,
a.[state_id] = #State_ID,
a.[postalcode] = #PostalCode,
a.[mobile] = #Mobile
FROM [auseraddress] a
INNER JOIN AUser b
ON a.Email = b.Email
WHERE b.email = #OriginalEmail
Your stored procedure is wrong.
According to your image the AUserAddress tables does not contain a column called Email.
I currently have an update statement running in c# and the front end to edit some values in my sql server database. But I am getting a Conversion Failed error. I can not seem to find the source.
ERROR message
Conversion failed when converting the nvarchar value 'UPDATE T_ROLLUP_SYSTEM_EXCEPT
SET DEPT_ID = ' to data type int.
14
Sql
ALTER PROCEDURE [dbo].[USP_UPDATE_SYS_MAPPING]
-- Add the parameters for the stored procedure here
#SYSTEM VARCHAR(50),
#UNIT VARCHAR(50),
#MEDCTRLEVEL VARCHAR(50),
#MEDCTR VARCHAR(50),
#FACID VARCHAR(50),
#ENTN VARCHAR(50),
#DEPT_ID INT,
#ROLLUP_TYPE_ID INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #SQL VARCHAR(MAX);
DECLARE #MEDCTRID INT;
SELECT #MEDCTRID = MED_CTR_ID FROM T_ROLLUP_MED_CTR WHERE MED_CTR = #MEDCTR
PRINT (#MEDCTRID);
-- Insert statements for procedure here
SET #SQL = N'UPDATE T_ROLLUP_SYSTEM_EXCEPT
SET DEPT_ID =
'''+#DEPT_ID''' , ROLLUP_TYPE_ID = '''+#ROLLUP_TYPE_ID+'''
, UPDATE_DT = GETDATE()
WHERE SYSTEM = '''+#SYSTEM+'''
AND ENTN = '''+#ENTN+'''
AND MED_CTR_ID = '+CONVERT(VARCHAR,#MEDCTRID)+'
AND MED_CTR_LEVEL = '''+#MEDCTRLEVEL+'''
AND FAC_ID = '''+#FACID+'''
AND UNIT = '''+#UNIT+''''
PRINT (#SQL);
EXEC (#SQL);
HTML
string[] mdctrvalue = medctr.Text.Split('[', ']');
string[] mpvalue = mpSearch.Text.Split('(', ')');
string sys = acctsys.ToString();
string unit = txtunit.ToString();
string mdctrlvl = mdctrvalue[1].ToString();
string mdctr = mdctrvalue[0].ToString();
string facid = fac.ToString();
string entn = txtentn.ToString();
string dept_id = dept.SelectedValue.ToString();
string rollup_type_id = rolluptype.SelectedValue.ToString();
SqlConnection myconn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Rollup2ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = myconn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "USP_UPDATE_SYS_MAPPING";
cmd.Parameters.Add("#SYSTEM", SqlDbType.VarChar).Value = acctsys.ToString();
cmd.Parameters.Add("#UNIT", SqlDbType.VarChar).Value = unit.ToString();
cmd.Parameters.Add("#MEDCTRLEVEL", SqlDbType.VarChar).Value = mdctrlvl.ToString();
cmd.Parameters.Add("#MEDCTR", SqlDbType.VarChar).Value = mdctr.ToString();
cmd.Parameters.Add("#FACID", SqlDbType.VarChar).Value = facid.ToString();
cmd.Parameters.Add("#ENTN", SqlDbType.VarChar).Value = entn.ToString();
cmd.Parameters.Add("#DEPT_ID", SqlDbType.Int).Value = dept_id.ToString();
cmd.Parameters.Add("#ROLLUP_TYPE_ID", SqlDbType.Int).Value = rollup_type_id.ToString();
myconn.Open();
int retVal = cmd.ExecuteNonQuery();
Maybe change:
+#ROLLUP_TYPE_ID+
To:
+ CONVERT(VARCHAR(12), #ROLLUP_TYPE_ID) +
You should always specify a length for your varchar columns/variables...
That said, you can re-write your stored procedure to not use dynamic SQL at all - why is it being used?
ALTER PROCEDURE [dbo].[USP_UPDATE_SYS_MAPPING]
#SYSTEM VARCHAR(50),
#UNIT VARCHAR(50),
#MEDCTRLEVEL VARCHAR(50),
#MEDCTR VARCHAR(50),
#FACID VARCHAR(50),
#ENTN VARCHAR(50),
#DEPT_ID INT,
#ROLLUP_TYPE_ID INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #MEDCTRID INT;
SELECT #MEDCTRID = MED_CTR_ID FROM dbo.T_ROLLUP_MED_CTR
WHERE MED_CTR = #MEDCTR;
PRINT (#MEDCTRID);
UPDATE dbo.T_ROLLUP_SYSTEM_EXCEPT
SET DEPT_ID = CASE
WHEN #DEPT_ID > 1 THEN #DEPT_ID
WHEN #DEPT_ID = 1 THEN NULL
ELSE REG_DEPT_ID1 END
, ROLLUP_TYPE_ID = #ROLLUP_TYPE_ID
, UPDATE_DT = GETDATE()
WHERE SYSTEM = #SYSTEM
AND ENTN = #ENTN
AND MED_CTR_ID = #MEDCTRID
AND MED_CTR_LEVEL = #MEDCTRLEVEL
AND FAC_ID = #FACID
AND UNIT = #UNIT;
END
GO
If it needs to be dynamic SQL for some reason you haven't yet shared, you are still better off parameterizing as much of this as possible using sp_executesql instead of EXEC().