Related
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'm trying to add a new user to table using a SQL Server stored procedure, but it's not being added, and it does not shows any errors, either.
C# code:
public void ADD_USER(string firstname, string lastname, string username, string password, string birthdate, string shiftstart, string shiftend, string ssn, string address, int salary, byte[] id_image, byte[] avatar)
{
DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
DAL.Open();
SqlParameter[] param = new SqlParameter[12];
param[0] = new SqlParameter("#USERNAME", SqlDbType.VarChar,100);
param[0].Value = username;
param[1] = new SqlParameter("#PASSWORD", SqlDbType.VarChar, 100);
param[1].Value = password;
param[2] = new SqlParameter("#FIRSTNAME", SqlDbType.VarChar, 100);
param[2].Value = firstname;
param[3] = new SqlParameter("#LASTNAME", SqlDbType.VarChar, 100);
param[3].Value = lastname ;
param[4] = new SqlParameter("#BIRTHDATE", SqlDbType.Date);
param[4].Value = birthdate;
param[5] = new SqlParameter("#ADDRESS", SqlDbType.VarChar, 100);
param[5].Value = address;
param[6] = new SqlParameter("#SSN", SqlDbType.Int);
param[6].Value = ssn;
param[7] = new SqlParameter("#SHIFTSTART", SqlDbType.Time);
param[7].Value = shiftstart;
param[8] = new SqlParameter("#SHIFTEND", SqlDbType.Time);
param[8].Value = shiftend;
param[9] = new SqlParameter("#SALARY", SqlDbType.Int);
param[9].Value = salary;
param[10] = new SqlParameter("#ID_IMAGE", SqlDbType.Image);
param[10].Value = id_image;
param[11] = new SqlParameter("#AVATAR", SqlDbType.Image);
param[11].Value = avatar;
try
{
DAL.executeCommand("ADD_USER", param);
}
catch (SqlException ex)
{
Console.Write(ex.Message);
}
DAL.close();
}
Stored procedure code:
CREATE PROC ADD_USER
#USERNAME VARCHAR(100),
#PASSWORD VARCHAR(100),
#FIRSTNAME VARCHAR(100),
#LASTNAME VARCHAR(100),
#BIRTHDATE VARCHAR(100),
#ADDRESS VARCHAR(100),
#SSN INT,
#ID_IMAGE IMAGE,
#AVATAR IMAGE,
#SHIFTSTART VARCHAR(100),
#SHIFTEND VARCHAR(100),
#SALARY INT
AS
INSERT INTO [CAFE].[dbo].[users] ([username], [password],
[firstname], [lastname], [SSN],
[id_image], [avatar],
[start_working], [shift_start], [shift_end],
[salary], [birth_date], [address])
VALUES (#USERNAME, #PASSWORD,
#FIRSTNAME, #LASTNAME, #SSN,
#ID_IMAGE, #AVATAR,
CONVERT(DATE, GETDATE()), #SHIFTSTART, #SHIFTEND,
#SALARY, #BIRTHDATE, #ADDRESS)
The stored procedure works fine on SQL Server itself, but doesn't add any records from C# code
I tried to trace this issue but I didn't get a result.
I'm using SQL Server 2008 R2 And Visual Studio 2015
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;
}
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 have worked on this, but unable to figure why my update fails. I'm not big on SQL. I wrote a simple stored procedure.
Here is the code:
CREATE PROCEDURE [dbo].sp_UpdateTeamMemberProfile
#TeamMemberId int OUTPUT,
#FirstName varchar(25),
#LastName varchar(30),
#ContactNumber varchar (20),
#ContactExt varchar (20) ,
#EmailAddress varchar(100),
#Fax varchar (25),
#LocationCity varchar (20),
#LocationState varchar (20),
#BeginWorkHrs int,
#BeginWorkTime varchar (20) ,
#EndWorkHrs int ,
#EndWorkTime varchar (20) ,
#ZONE Varchar (20),
#TeamMemberLanId varchar (20),
#ManagerId varchar (20),
#UpdateDate datetime
AS
BEGIN
SET NOCOUNT ON;
BEGIN
UPDATE dbo.LoanOwnerStamp
SET FirstName = #FirstName,
LastName = #LastName,
ContactNumber = #ContactNumber,
ContactExt = #ContactExt ,
EmailAddress = #EmailAddress,
Fax = #Fax,
LocationCity = #LocationCity,
LocationState = #LocationState,
BeginWorkHrs = #BeginWorkHrs,
BeginWorkTime = #BeginWorkTime,
EndWorkHrs = #EndWorkHrs,
EndWorkTime = #EndWorkTime,
Zone = #Zone,
TeamMemberLanId = #TeamMemberLanId,
ManagerId = #ManagerId ,
UpdatedDate = #UpdateDate
WHERE
TeamMemberLanId = #TeamMemberLanId
AND TeamMemberId = #TeamMemberId
END
SET #TeamMemberId = SCOPE_IDENTITY()
RETURN #TeamMemberId
END
Now the code behind follows...
using (SqlCommand updatetLSTeamMember = new SqlCommand("sp_UpdateTeamMemberProfile", myConnection))
{
updatetLSTeamMember.CommandType = CommandType.StoredProcedure;
updatetLSTeamMember.Parameters.Add("#FirstName", SqlDbType.VarChar, 25).Value = txtFirstName.Text;
updatetLSTeamMember.Parameters.Add("#LastName", SqlDbType.VarChar, 30).Value = txtLastName.Text;
updatetLSTeamMember.Parameters.Add("#ContactNumber", SqlDbType.VarChar, 20).Value = txtContactNumber.Text;
updatetLSTeamMember.Parameters.Add("#ContactExt", SqlDbType.VarChar, 20).Value = txtContactExt.Text;
updatetLSTeamMember.Parameters.Add("#EmailAddress", SqlDbType.VarChar, 100).Value = txtEmailAddress.Text;
updatetLSTeamMember.Parameters.Add("#Fax", SqlDbType.VarChar, 25).Value = txtFax.Text;
updatetLSTeamMember.Parameters.Add("#LocationCity", SqlDbType.VarChar, 20).Value = txtLocationCity.Text;
updatetLSTeamMember.Parameters.Add("#LocationState", SqlDbType.VarChar, 20).Value = txtState.Text;
updatetLSTeamMember.Parameters.Add("#BeginWorkHrs", SqlDbType.Int).Value = ddlBeginHrs.SelectedValue.ToString();
updatetLSTeamMember.Parameters.Add("#BeginWorkTime", SqlDbType.VarChar, 20).Value = ddlBeginTime.SelectedValue.ToString();
updatetLSTeamMember.Parameters.Add("#EndWorkHrs", SqlDbType.Int).Value = ddlEndHrs.SelectedValue.ToString();
updatetLSTeamMember.Parameters.Add("#EndWorkTime", SqlDbType.VarChar, 20).Value = ddlEndTime.SelectedValue.ToString();
updatetLSTeamMember.Parameters.Add("#Zone", SqlDbType.VarChar, 20).Value = ddlZone.SelectedItem.Text;
updatetLSTeamMember.Parameters.Add("#TeamMemberLanId", SqlDbType.VarChar, 20).Value = txtTeamMemberLaniId.Text;
updatetLSTeamMember.Parameters.Add("#ManagerId", SqlDbType.VarChar, 20).Value = gblUserId;
updatetLSTeamMember.Parameters.Add("#UpdateDate", SqlDbType.DateTime).Value = DateTime.Now.ToLocalTime();
pID = updatetLSTeamMember.Parameters.Add("#TeamMemberId", SqlDbType.Int); // I'm thinking this is a culprit
pID.Direction = ParameterDirection.Output; // are these assignment correct.
try
{
if (updatetLSTeamMember.Connection.State == ConnectionState.Closed)
{
updatetLSTeamMember.Connection.Open();
}
updatetLSTeamMember.ExecuteNonQuery(); // code bombs out here
string idcat = updatetLSTeamMember.Parameters["#TeamMemberId"].Value.ToString();
Now my questions are in several places, is my Parameter.Direction output correct and is it correct from a stored procedure perspective?
Any help is appreciated.
If you want to return a value I would suggest creating another variable in the stored procedure instead of using a value that you use for input.
This is what I would do:
#returnValue int OUTPUT
#TeamMemberId int,
#FirstName varchar(25),
#LastName varchar(30),
#ContactNumber varchar (20),
#ContactExt varchar (20) ,
#EmailAddress varchar(100),
#Fax varchar (25),
#LocationCity varchar (20),
#LocationState varchar (20),
#BeginWorkHrs int,
#BeginWorkTime varchar (20) ,
#EndWorkHrs int ,
#EndWorkTime varchar (20) ,
#ZONE Varchar (20),
#TeamMemberLanId varchar (20),
#ManagerId varchar (20),
#UpdateDate datetime
AS
BEGIN
SET NOCOUNT ON;
UPDATE dbo.LoanOwnerStamp
SET FirstName = #FirstName,
LastName = #LastName,
ContactNumber = #ContactNumber,
ContactExt = #ContactExt ,
EmailAddress = #EmailAddress,
Fax = #Fax,
LocationCity = #LocationCity,
LocationState = #LocationState,
BeginWorkHrs = #BeginWorkHrs,
BeginWorkTime = #BeginWorkTime,
EndWorkHrs = #EndWorkHrs,
EndWorkTime = #EndWorkTime,
Zone = #Zone,
TeamMemberLanId = #TeamMemberLanId,
ManagerId = #ManagerId ,
UpdatedDate = #UpdateDate
WHERE
TeamMemberLanId = #TeamMemberLanId
AND TeamMemberId = #TeamMemberId
SET #returnValue= SCOPE_IDENTITY()
RETURN #returnValue
END
And on your code behind:
EDIT:You also need to add this:
updatetLSTeamMember.Parameters.AddWithValue("#TeamMemberId", int.Parse(txtTeamMemberId.Text)); // or wherever you are getting the team member id from.
pID = updatetLSTeamMember.Parameters.Add("#returnValue", SqlDbType.Int);
pID.Direction = ParameterDirection.Output;
string idcat = updatetLSTeamMember.Parameters["#returnValue"].Value.ToString();
NOTE: I have never used SCOPE_IDENTITY() On an Update. You might want to look into that.
If you need to return something in case of success - u can use ##ROWCOUNT instead of SCOPE_IDENTITY() - it will return number of rows affected by the update.
So if 0 is returned - you will know that no records were updated.
I might be wrong but you're updating record based on where condition where you're using TeamMemberId (Output parameter), but not providing any value to it in c# side. The syntax si corect for output parameter but you're using it in where clause, what is the value,...
The Scope Identity part will be executed after executing the update command