Update stored procedure - SQL Server 2012 - sql

I have an error and I cannot find the reason for failing of this procedure. All I know it does something I have no clue about. Does anyone have an idea what is this about? :|
ALTER PROCEDURE [dbo].[updateAccountPersonJob]
#department nvarchar(50),
#description nvarchar(50),
#personID int,
#name nvarchar(50),
#surname nvarchar(50),
#email nvarchar(50),
#username nvarchar(50),
#password nvarchar(50),
#status nvarchar(50)
AS
BEGIN TRANSACTION
DECLARE #missionID int, #jobID int;
BEGIN TRY
SET #jobID = (SELECT id FROM Jobs
WHERE department = #department AND description = #description)
UPDATE Persons
SET name = #name, surname = #surname, email = #email, jobID = #jobID
WHERE Persons.id = #personID
UPDATE Accounts
SET Username = #username, Password = #password, Status = #status
WHERE Accounts.Password = #personID
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
BEGIN IF ##TRANCOUNT > 0
ROLLBACK TRANSACTION;
PRINT('ROLLBACK')
END
END CATCH;
IF ##TRANCOUNT > 0
COMMIT TRANSACTION;
EXEC:
EXEC [dbo].updateAccountPersonJob
#department = N'Facultatea de Matematica si Informatica',
#description = N'Teacher',
#personID = N'16',
#name = N'Dummy',
#surname = N'BarFOO',
#email = N'bar#ba.com',
#username = N'dummy',
#password = N'd',
#status = N'Teacher'
Error:
Conversion failed when converting the nvarchar value 'director' to data type int.

you are checking personid (integer) column against password column which is nvarchar. Update you query to use correct parameter or column and your code should work

Related

Cursors taking too long time for 34million rows and sp is executed 34million times

I am using cursors to fetch rows from the table which has 34million data and passing it to a stored procedure , i mean passing each row data resulting in 34million times sp is called, How to avoid cursors or any solutions
I know its a long code, since many asked to put sp also I have given sp also
ALTER PROCEDURE [dbo].[UpdateConData]
(
#UId BIGINT
)
AS
BEGIN
DECLARE #sTime DATETIME
DECLARE #eTime DATETIME
DECLARE #res NVARCHAR(30)
DECLARE #uId INT
DECLARE #Email NVARCHAR(256)
DECLARE #rCount TINYINT
DECLARE #sCount TINYINT
DECLARE conCursor CURSOR FAST_FORWARD LOCAL FOR
SELECT STime,ETime,res,uId,Email,
c.RCount,c.SCount FROM PCon c
OPEN conCursor
FETCH NEXT FROM conCursor INTO
#sTime, #eTime, #res, #uId, #Email,
#rCount, #sCount
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC InsertOrUpdateSCon #sTime, #eTime, #res, #uId, #Email,
#rCount, #sCount
UPDATE records
SET
ETime = #eTime
WHERE PId = #pId AND Type='Sync' and Integer1 = #uId
FETCH NEXT FROM conversationCursor INTO
#sTime, #eTime, #res, #uId, #Email,
#rCount, #sCount
END
CLOSE conCursor
DEALLOCATE conCursor
END
CREATE PROCEDURE [dbo].[InsertOrUpdateSCon]
(
#sTime DATETIME,
#eTime DATETIME,
#res NVARCHAR(30),
#uId BIGINT,
#EmailNVARCHAR(256),
#rCount TINYINT,
#sCount TINYINT
)
AS
BEGIN
DECLARE #conId INT
DECLARE #dId INT
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION SCon
EXEC InsertOrUpdateSDP #sTime, #uId, #Email, #dId OUTPUT
MERGE Con WITH (HOLDLOCK) a USING
(SELECT 'Email' AS Type, #res AS Dson, #Email AS MeData,
#uId AS UId, #sTime AS STime) AS b
ON a.Type=b.Type AND a.Dson=b.Dson AND a.MeData=b.MeData AND a.UId=b.UId AND a.STime=b.STime
WHEN MATCHED THEN
UPDATE SET RCount=RCount + #rCount,
SCount=SCount + #sCount
WHEN NOT MATCHED THEN
INSERT(DId, [Type], Dson, MeData, UId,
STime, ETime, SCount, RCount)
VALUES(#dId, b.Type, #res, #Email, #uId,
#sTime, #eTime, #sCount, #rCount);
COMMIT TRANSACTION SCon
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
END
CREATE PROCEDURE [dbo].[InsertOrUpdateSDP ]
(
#sTime DATETIME,
#uId BIGINT,
#Email NVARCHAR(256),
#dId INT OUTPUT
)
AS
BEGIN
SELECT TOP 1 #dId = DP.PId FROM DP
INNER JOIN Email E ON E.PId=DP.PId AND E.Email=#Email
WHERE PId = 1 /* Email */ AND UId = #dId
IF #dId IS NULL
BEGIN
DECLARE #now DATETIME = GETUTCDATE()
INSERT INTO tableA ([Type], CTime, LTime, IsActive, IsNotactive)
VALUES(1, #now, #now, 0, 1)
SET #dId = SCOPE_IDENTITY()
INSERT INTO tableB(PId, STime, SSTime, DId, UId, SP)
VALUES(#dId, #sTime, #stTime, 1, #Id, 1)
INSERT INTO tableC(PId, Email, DOr, DNS)
VALUES(#dID, #Email, 0, RIGHT(#Email,
LEN(#Email) - CHARINDEX('#', #Email)))
END
ELSE
BEGIN
UPDATE DP SET
SMTime = #sTime,
SP = 1
WHERE PId = #dId AND SMTime < #sTime
END
END

Cannot rollback in if block transaction sql

When I executed this stored procedure, I cannot rollback in IF block even the IF statement was right. If the IF statement was right, script still running in the end and there is no rollback at all.
The message: The account id has already used successful register
Msg 3902, Level 16, State 1, Procedure PROC_DANGKY, Line 23
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
Code:
CREATE PROCEDURE PROC_REGISTER
#name nvarchar(30),
#birth datetime,
#passport nvarchar(9),
#address nvarchar(50),
#phone nvarchar(11),
#email nvarchar(20),
#account nvarchar(30),
#password nvarchar(20)
AS
BEGIN TRAN
BEGIN TRY
IF (EXISTS(SELECT * FROM CUSTOMER WHERE ACCOUNT = #account))
BEGIN
PRINT N'The account id has already been used'
ROLLBACK TRAN
END
INSERT INTO KHACHHANG
VALUES (#name, #birth, #passport, #address, #phone, #email, #account, #password)
PRINT N'Successfully registered'
END TRY
BEGIN CATCH
DECLARE #ErrorMsg VARCHAR(2000)
SELECT #ErrorMsg = N'Error: ' + ERROR_MESSAGE()
RAISERROR(#ErrorMsg, 16,1)
ROLLBACK TRAN
RETURN
END CATCH
COMMIT TRAN
REFORMATTED your query
Removed rollback after exists
CREATE PROC PROC_REGISTER
#name nvarchar(30),
#birth datetime,
#passport nvarchar(9),
#address nvarchar(50),
#phone nvarchar(11),
#email nvarchar(20),
#account nvarchar(30),
#password nvarchar(20)
AS
BEGIN TRAN
BEGIN TRY
IF (EXISTS(SELECT * FROM CUSTOMER WHERE ACCOUNT = #account))
PRINT N'The account id has already used'
ELSE
BEGIN
INSERT INTO KHACHHANG VALUES (#name, #birth, #passport, #address, #phone, #email, #account, #password)
PRINT N'Successul register'
END
END TRY
BEGIN CATCH
DECLARE #ErrorMsg VARCHAR(2000)
SELECT #ErrorMsg = N'Error: ' + ERROR_MESSAGE()
RAISERROR(#ErrorMsg, 16,1)
IF ##TRANCOUNT > 0
ROLLBACK TRAN
END CATCH
IF ##TRANCOUNT > 0
COMMIT TRAN
GO
RETURN
You can check ##TRANCOUNT before rollback to ckeck if transaction exists:
CREATE PROC PROC_REGISTER
#name nvarchar(30),
#birth datetime,
#passport nvarchar(9),
#address nvarchar(50),
#phone nvarchar(11),
#email nvarchar(20),
#account nvarchar(30),
#password nvarchar(20)
AS
BEGIN TRAN
BEGIN TRY
IF (EXISTS(SELECT * FROM CUSTOMER WHERE ACCOUNT = #account))
BEGIN
PRINT N'The account id has already used'
IF (##TRANCOUNT > 0)
BEGIN
ROLLBACK TRAN
END
END
INSERT INTO KHACHHANG VALUES (#name, #birth, #passport, #address, #phone, #email, #account, #password)
PRINT N'Successul register'
END TRY
BEGIN CATCH
DECLARE #ErrorMsg VARCHAR(2000)
SELECT #ErrorMsg = N'Error: ' + ERROR_MESSAGE()
RAISERROR(#ErrorMsg, 16,1)
IF (##TRANCOUNT > 0)
BEGIN
ROLLBACK TRAN
END
RETURN
END CATCH
COMMIT TRAN

RAISERROR Dosn't Work Inside CATCH With ROLLBACK TRANSACTION

I created a Stored Procedure to Insert Into 2 Table With Transaction to make sure That Both Inserts Done and I Used TRY and CATCH to Handle The Errors .. The Problem Is In The Catch Statement I Put ROLLBACK TRANS and RAISERROR The RoLLBACK Works But The Procedure Dose not RAISERROR
Here is The Code
ALTER PROC SP_InsertPlot
#PlotName nvarchar(50),
#GrossArea int,
#SectorName Nvarchar(50),
#PlotYear int,
#OwnerName Nvarchar(50),
#Remarks text,
#NumberOfPlants INT,
#NetArea INT,
#Category Nvarchar(50),
#Type Nvarchar(50),
#Variety Nvarchar(50),
#RootStock Nvarchar(50),
#PlantDistance Decimal(18,2)
AS
BEGIN
DECLARE #PlotID INT
SET #PlotID = (SELECT ISNULL(MAX(PlotID),0) FROM Plots) + 1
DECLARE #SectorID INT
SET #SectorID = (SELECT SectorID FROM Sectors WHERE SectorName = #SectorName)
DECLARE #OwnerID INT
SET #OwnerID = ( SELECT OwnerID FROM Owners WHERE OwnerName = #OwnerName)
DECLARE #CategoryID INT
SET #CategoryID = (SELECT CategoryID FROM Categories WHERE CategoryName = #Category)
DECLARE #TypeID INT
SET #TypeID = (SELECT TypeID FROM Types WHERE TypeName = #Type)
DECLARE #VarietyID INT
SET #VarietyID = (SELECT VarietyID FROM Varieties WHERE VarietyName = #Variety)
DECLARE #RootStockID INT
SET #RootStockID = (SELECT RootStockID FROM RootStocks WHERE RootStockName = #RootStock)
DECLARE #PlotDescID INT
SET #PlotDescID = (SELECT ISNULL(MAX(PlotDescID),0) FROM PlotDescriptionByYear) + 1
BEGIN TRY
SET XACT_ABORT ON
SET NOCOUNT ON
IF(SELECT Count(*) FROM Plots WHERE PlotName = #PlotName) = 0
BEGIN
BEGIN TRANSACTION
INSERT INTO Plots (PlotID,PlotName,GrossArea,SectorID,PlantYear,OnwerID,Remarks)
VALUES(#PlotID,#PlotName,#GrossArea,#SectorID,#PlotYear,#OwnerID,#Remarks)
INSERT INTO PlotDescriptionByYear (PlotDescID, PlantYear, NumberOfPlants,PlotID,NetArea,CategoryID,TypeID,VarietyID,RootStockID,PlantDistance)
VALUES(#PlotDescID,YEAR(GETDATE()),#NumberOfPlants,#PlotID -1,#NetArea,#CategoryID,#TypeID,#VarietyID,#RootStockID,#PlantDistance)
COMMIT TRANSACTION
END
END TRY
BEGIN CATCH
IF(XACT_STATE())= -1
BEGIN
ROLLBACK TRANSACTION
RAISERROR('This Plot Is Already Exists !!',11,1)
END
END CATCH
END
By the way i tried to change the Severity and I tried ##TRANCOUNT instead of XACT_STATE and the Same Problem Happens Which is When I Exec Proc and Pass an Existing Data To The Parameters The Transaction Roll back and did not rise the error
Change IF(XACT_STATE())= -1 to IF(XACT_STATE()) <> 0 and your problem will be done.

Transaction count after EXECUTE indicates mismatching number of BEGIN and COMMIT statements

When I execute the below stored procedure I get this error:
System.Data.SqlClient.SqlException: Transaction count after EXECUTE
indicates a mismatching number of BEGIN and COMMIT statements.
Previous count = 0, current count = 1.
Code:
create procedure [dbo].[sp_crm_diler_master]
(
#Fullname varchar(100),
#Email varchar(50),
#Mobile varchar(12),
#qualification varchar(50),
#presentaddress varchar(250),
#permanentaddress varchar(250),
#location varchar(50),
#skills varchar(100),
#Dob varchar(15),
#myphoto varbinary(Max),
#uniqueid varchar(25),
#Message varchar(150) output
)
AS
BEGIN
if not exists (select emailid,phone from crm_masterdata where emailid=#Email And phone=#Mobile)
begin
begin transaction
declare #small smalldatetime = (select CAST(#Dob as smalldatetime))
declare #todaydate datetime=(select getdate())
insert into crm_masterdata(uniqueid,fullname,phone,dob,photo,emailid,qualification,location,present_address,permanent_address,skillsets,datasource,entrydate,active)
values(#uniqueid,#Fullname,#Mobile,#small,#myphoto,#Email,#qualification,#location,#presentaddress,#permanentaddress,#skills,'reception',#todaydate,1)
Set #Message=' Registration Successfull,Please Login'
end
else
begin
set #Message='This User Already Registered'
end
end
Where is my error?
create procedure [dbo].[sp_crm_diler_master]
(
#Fullname varchar(100),
#Email varchar(50),
#Mobile varchar(12),
#qualification varchar(50),
#presentaddress varchar(250),
#permanentaddress varchar(250),
#location varchar(50),
#skills varchar(100),
#Dob varchar(15),
#myphoto varbinary(Max),
#uniqueid varchar(25),
#Message varchar(150) output
)
AS
BEGIN
SET NOCOUNT ON;
declare #small smalldatetime = (select CAST(#Dob as smalldatetime));
declare #todaydate datetime=getdate();
declare #Error INT;
BEGIN TRANSACTION; --<-- You need to commit it
IF not exists (select 1 from crm_masterdata where emailid=#Email And phone=#Mobile)
BEGIN
insert into crm_masterdata(uniqueid,fullname,phone,dob,photo,emailid
,qualification,location,present_address,permanent_address,skillsets,datasource,entrydate,active)
values(#uniqueid,#Fullname,#Mobile,#small,#myphoto,#Email,#qualification
,#location,#presentaddress,#permanentaddress,#skills,'reception',#todaydate,1)
SET #Error = ##ERROR;
Set #Message =' Registration Successfull,Please Login'
END
ELSE
BEGIN
SET #Message='This User Already Registered'
END
IF (#Error = 0)
COMMIT TRANSACTION; --<-- Commit tran
ELSE
ROLLBACK TRANSACTION;
END
I don't see a COMMIT TRANSACTION to match your BEGIN TRANSACTION.

Procedure or function has too many arguments SQL server

I getting this error while executing the stored procedure in SQL Server:
Msg 8144, Level 16, State 2, Procedure sp_adduser, Line 2
Procedure or function sp_adduser has too many arguments specified.
The weird thing is that the number of parameters is the same as declared in the procedure, even when I execute it while right-click on the procedure and press execute, input the parameters from the fields and still the same error.
This is the code of the procedure and the exec:
create procedure [dbo].[sp_addUser]
(
#userID nvarchar(50),
#pw nvarchar(50),
#fName nvarchar(50),
#lname nvarchar(50),
#email nvarchar(150),
#address nvarchar(150),
#city int,
#country int,
#phone nvarchar(50),
#gender nvarchar(10),
#dob date,
#photo nvarchar(150),
#secq int,
#secAnswer nvarchar(150),
#completed int output)
as
declare #found int
/*
usertype:
0 - Administrator
1 - User
*/
begin
begin
select #found=count(*) from registration r
where REPLACE(r.firstname,' ','')=REPLACE(#fName,' ','')
and REPLACE(r.lastname,' ','')=REPLACE(#lname,' ','')
and r.dateofbirth=#dob;
end
begin
if #found=0
begin
begin
insert into Login values(#userID,#pw,0,1);
end
begin
insert into registration values(
#userID,#fName,#lname,#email,
#address,#city,#country,#phone,
#gender,#dob,#photo,#secq,#secAnswer
)
end
begin
set #completed=1;
end
end
else set #completed=0
end
return #completed
end
And here is the exec:
DECLARE #return_value int,
#completed int
SELECT #completed = 0
EXEC #return_value = [dbo].[sp_addUser]
#userID = N'a',
#pw = N'a',
#fName = N'a',
#lname = N'a',
#email = N'a',
#address = N'a',
#city = 1,
#country = 1,
#phone = N'a',
#gender = N'a',
#dob = '01/01/2000',
#photo = N'a',
#secq = 1,
#secAnswer = N'a',
#completed = #completed OUTPUT
SELECT #completed as N'#completed'
SELECT 'Return Value' = #return_value
Thanks in advance!
sp_adduser is a procedure which is built-in to SQL Server - see https://msdn.microsoft.com/en-us/library/ms181422.aspx
Don't use the sp_ prefix for your own stored procedures, maybe call it proc_adduser instead, I think that will work
You are actually calling the system stored procedure sp_adduser. The "sp_" prefix is special and has its own rules on resolution, so using it is recommended against. If you want to use your own prefix, whatever you do, don't use "sp_".
Per #marc_s, even if your stored procedure doesn't clash with an existing system stored procedure, you will still get a noticeable performance hit due to cache misses.