i tried to insert data in database using stored procedure but according to some condition. for example if data is already exists in database the the stored procedure should not be executed.
i am doing the following code but it return 0 every time rather then i want. What can i do
ALTER PROCEDURE dbo.SaveUser
(
#cid int,
#firstname varchar(20),
#lastname varchar(20),
#dob datetime,
#gender varchar(20),
#add varchar(100),
#email varchar(40),
#quali varchar(20),
#yop varchar(15),
#exp varchar(10),
#pass varchar(20)
)
AS
declare #result int
if EXISTS( select Email_ID from Registration where Email_ID=#email )
begin
set #result=4;
return #result;
end
else
begin
insert into Registration values(#cid, #firstname, #lastname, #dob, #gender, #add, #email, #quali, #yop, #exp, #pass );
set #result =0;
return #result;
end
You can simply proceed as follows;
ALTER PROCEDURE dbo.SaveUser
(
#cid int,
#firstname varchar(20),
#lastname varchar(20),
#dob datetime,
#gender varchar(20),
#add varchar(100),
#email varchar(40),
#quali varchar(20),
#yop varchar(15),
#exp varchar(10),
#pass varchar(20)
)
AS
BEGIN
DECLARE #return int
if NOT EXISTS(select Email_ID from Registration where Email_ID=#email)
insert into Registration values(#cid, #firstname, #lastname,
#dob, #gender, #add, #email,
#quali, #yop, #exp, #pass )
If (##ERROR <> 0)
Begin
Set #return = 4
Else
Set #return = 0
End
Return #return
END
You can use raiseerror event for this scenario
if EXISTS( select Email_ID from Registration where Email_ID=#email )
begin
RAISERROR(N'Email id already exist.', 10, 2,'')
end
Here 10 is severity level and according to severity level sql server identified as info meassage or exception. For more information
RaiseError
Database Engine Severity Levels
Try this one -
ALTER PROCEDURE dbo.SaveUser
(
#cid INT,
#firstname VARCHAR(20),
#lastname VARCHAR(20),
#dob DATETIME,
#gender VARCHAR(20),
#add VARCHAR(100),
#email VARCHAR(40),
#quali VARCHAR(20),
#yop VARCHAR(15),
#exp VARCHAR(10),
#pass VARCHAR(20)
)
AS BEGIN
IF NOT EXISTS(
SELECT 1
FROM dbo.Registration
WHERE Email_ID = #email
) BEGIN
INSERT INTO dbo.Registration
SELECT #cid, #firstname, #lastname, #dob, #gender, #add, #email, #quali, #yop, #exp, #pass
RETURN 0;
END
RETURN 4;
END
Related
I understand the error, I am simply not sure why this is occurring. I have written a simple insert procedure to update a list of users.
Error:
Msg 206, Level 16, State 2, Procedure addNewUser, Line 0 [Batch Start Line 2]
Operand type clash: int is incompatible with date
Procedure declaration:
CREATE PROCEDURE [dbo].[addNewUser]
#fName VARCHAR(255),
#lname VARCHAR(255),
#dob DATE,
#email VARCHAR(255),
#gender VARCHAR(255),
#level VARCHAR(255) AS
INSERT INTO [dbo].[User] ([firstname], [lastname], [dob], [email], [gender], [accesslevel])
VALUES ('#fName ', N'#lname', #dob, N'#email', N'#gender', N'#level')
Calling procedure:
DECLARE #return_value int
EXEC #return_value = [dbo].[addNewUser]
#fName = N'Ste',
#lname = N'King',
#dob = 19780103,
#email = N'Books#email.com',
#gender = N'Male',
#level = N'Free'
SELECT 'Return Value' = #return_value
GO
Just put #dob = 19780103 into quotes '1978-01-03':
USE [t7068097]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[addNewUser]
#fName = N'Ste',
#lname = N'King',
#dob = '1978-01-03',
#email = N'Books#email.com',
#gender = N'Male',
#level = N'Free'
SELECT 'Return Value' = #return_value
GO
UPDATE:
SELECT CAST('1978-1-1' AS DATE)
SELECT CAST('19780101' AS DATE)
First your procedure is wrong. You shouldn't put your variables into the single quote for your purpose:
ALTER PROCEDURE [dbo].[addNewUser]
#fName varchar(255),
#lname varchar(255),
#dob DATE,
#email varchar(255),
#gender varchar(255),
#level varchar(255)
AS
INSERT [dbo].[User]
(
[firstname]
, [lastname]
, [dob]
, [email]
, [gender]
, [accesslevel]
)
VALUES
(
#fName
, #lname
, #dob
, #email
, #gender
, #level
)
GO
Also you send int value to the date field. You need yo put into the single quote:
DECLARE #return_value int
EXEC #return_value = [dbo].[addNewUser]
#fName = N'Ste',
#lname = N'King',
#dob = '19780103',
#email = N'Books#email.com',
#gender = N'Male',
#level = N'Free'
SELECT 'Return Value' = #return_value
Query returns exactly what I want but when I plug the same structure into my stored Procedure I get a formatting error.
Msg 8116, Level 16, State 1, Procedure RegisterUser, Line 21
Argument data type varchar is invalid for argument 1 of format function.
Here's my query.
DECLARE #Department int
SET #Department = (SELECT DepartmentLink FROM DepartmentMaster WHERE Name =
'Inventory')
DECLARE #Position int
SET #Position = (SELECT TypeLink FROM EmployeeTypes Where Title = 'Clerk')
DECLARE #UID int
set #UID = (SELECT ID FROM EmployeeMaster WHERE FirstName = 'John' and
LastName = 'Doe')
(SELECT convert(varchar,FORMAT (#Department,'00#'))+'-'+
convert(varchar,FORMAT(#Position, '0#'))+'-
'+convert(varchar,FORMAT(#UID,'000#')) as EmployeeID)
Here's my Stored Procedure..
CREATE Procedure RegisterUser
(
#FirstName varchar(255),
#LastName varchar(255),
#Department varchar(255),
#Email varchar(255),
#Password varchar(255),
#UserType varchar(255),
#EmployeeID varchar(255),
#DepartmentLink int,
#Position int,
#UID int
)
AS
SET #Department = (SELECT DepartmentLink FROM DepartmentMaster WHERE Name =
#Department)
SET #Position = (SELECT TypeLink FROM EmployeeTypes Where Title = #UserType)
set #UID = (SELECT ID FROM EmployeeMaster WHERE FirstName = #FirstName and
LastName = #LastName)
SET #EmployeeID = (SELECT convert(varchar,FORMAT (#Department,'00#'))+'-'+
convert(varchar,FORMAT(#Position, '0#'))+'-
'+convert(varchar,FORMAT(#UID,'000#')) as EmployeeID)
INSERT INTO EmployeeMaster(FirstName, LastName, Department,
Email,Password,CreationDate, EmployeeID, Active)
VALUES(#FirstName, #LastName, (SELECT DepartmentLink FROM DepartmentMaster
WHERE Name = #Department), #Email, #Password, GETDATE(),
#EmployeeID
,1)
I would suggest writing this as:
CREATE Procedure RegisterUser (
#FirstName varchar(255),
#LastName varchar(255),
#Department varchar(255),
#Email varchar(255),
#Password varchar(255),
#UserType varchar(255),
#EmployeeID varchar(255),
#DepartmentLink int,
#Position int,
#UID int
) AS
BEGIN
DECLARE #DepartmentLink varchar(255);
DECLARE #PositionLink int;
DECLARE #Uid_new int;
DECLARE #EmployeeId_new varchar(255);
SELECT #DepartmentLink = DepartmentLink
FROM DepartmentMaster
WHERE Name = #Department;
SELECT #PostiionLink = TypeLink
FROM EmployeeTypes
WHERE Title = #UserType;
SELECT #Uid_new = ID
FROM EmployeeMaster
WHERE FirstName = #FirstName and LastName = #LastName;
SELECT #EmployeeID_new = (FORMAT(#Department, '00#') + '-' +
FORMAT(#Position, '0#')) + '-' +
FORMAT(#UID, '000#')
);
INSERT INTO EmployeeMaster(FirstName, LastName, Department, Email, Password, CreationDate, EmployeeID, Active)
VALUES(#FirstName, #LastName,
#DepartmentLink, #Email, #Password, GETDATE(),
#EmployeeID_new, 1
);
END; -- RegisterUser
You could simplify this further.
Notes:
Your code needs a BEGIN/END
Don't assign values to parameters, unless they are output parameters. Instead, use local variables.
FORMAT() already returning a string -- no need for another conversion.
SET with a subquery just looks awkward to me, when you can do the assignment with a SELECT.
I don't think you need all the arguments, but that is another matter.
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.
Can I please have some help with the syntax of a SP in SQL.
Here is my code:
CREATE PROCEDURE usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10)
)
AS
BEGIN
return #ID + #Description
END
CREATE PROCEDURE usp_InsertValue
(
#ID VARCHAR(10),
#FirstName VARCHAR(50),
#LastName VARCHAR(50),
#Description VARCHAR(10),
#Comment VARCHAR(max)
)
AS
BEGIN
Declare #v_Value VARCHAR(15)
Set #v_Value = usp_GetValue(#ID, #Description)
END
In the usp_InsertValue SP, I am wanting to declare and set a variable. Once the variable has been declared, I then wish to call another SP with parameters to set the value of the declared variable.
I am not sure of the syntax. May I please have some help?
UPDATE
I have updated my above code using your function. How do I Set the #v_Value from the usp_GetValue function.
I am getting this error:
'usp_GetValue' is not a recognized built-in function name.
UPDATE2
Here is my full code:
CREATE PROCEDURE usp_PersonCategoryLookupTesting
(
#ID VARCHAR(10),
#Description VARCHAR(10),
#res VARCHAR(10) OUTPUT
)
AS
BEGIN
return #ID + #Description
END
CREATE PROCEDURE usp_InsertPersonTesting
(
#IDTest VARCHAR(10),
#FirstName VARCHAR(50),
#LastName VARCHAR(50),
#AddressLine1 VARCHAR(50),
#AddressLine2 VARCHAR(50),
#AddressLine3 VARCHAR(50),
#MobilePhone VARCHAR(20),
#HomePhone VARCHAR(20),
#Description VARCHAR(10),
#Comment VARCHAR(max)
)
AS
BEGIN
Declare #PersonCategory VARCHAR(15)
EXEC usp_PersonCategoryLookupTest #ID, #Description, #PersonCategory
INSERT INTO Person(FirstName, LastName, AddressLine1, AddressLine2, AddressLine3, MobilePhone, HomePhone, DateModified, PersonCategory, Comment)
VALUES (#FirstName, #LastName, #AddressLine1, #AddressLine2, #AddressLine3, #MobilePhone, #HomePhone, GETDATE (), #PersonCategory, #Comment)
END
I am getting this error in my application that is calling the SQL code:
Conversion failed when converting the varchar value '123Client' to data type int.
I am using the values "123" and "Client" for #IDTest and #Description.
I think output parameters should be the proper way:
See this post:
stored procedure returns varchar
CREATE PROCEDURE usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10),
#res VARCHAR(10) OUTPUT
)
AS
BEGIN
return #ID + #Description
END
CREATE PROCEDURE usp_InsertValue
(
#ID VARCHAR(10),
#FirstName VARCHAR(50),
#LastName VARCHAR(50),
#Description VARCHAR(10),
#Comment VARCHAR(max)
)
AS
BEGIN
Declare #v_Value VARCHAR(15)
EXEC usp_GetValue #ID, #Description, #v_Value
-- use #v_Value here...
END
You can only use a function like that, not stored procedure. Stored Procedures only return integer values.
For SP, you need to create out parameters to retrieve the values. For this scenario, it is better to create a function
CREATE FUNCTION usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10),
)
RETURNS VARCHAR(50)
AS
BEGIN
return #ID + #Description
END
Then call it:
SET #v_value = dbo.usp_GetValue('John','Doe') --output: John Doe
If you insist you want a SP, which is not proper for this, there are 2 ways
1) An out parameter
CREATE PROCEDURE usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10),
#Result varchar(20) OUTPUT
)
AS
BEGIN
SET #Result = #ID + #Description
END
Then call it:
Declare #v_Value VARCHAR(15)
Set #v_Value = EXEC usp_GetValue #ID, #Description, #v_Value OUTPUT
2) Select from it
CREATE PROCEDURE usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10)
)
AS
BEGIN
SELECT #ID + #Description
END
Use it like this:
declare #tempresult as table(v_value as varchar(15))
INSERT INTO #tempresult
EXEC usp_GetValue #ID, #Description
Select Top 1 #v_value = v_value From #tempresult
My advise is use the function approach.
I have a table called 'tasks' in that 'task id' is identity column, for that table I have to write save stored procedure, in which when 'task id' is not given it should insert the values and when 'task id' is given it should update the table.
how can this achievable when task id is identity column could anyone explain with example.
here is the code
Alter PROCEDURE TaskSave
(
#taskid int,
#ProjectId int,
#EmployeeId int,
#TaskName nvarchar(50),
#Duration_Hrs int,
#StartDate nvarchar(20),
#FinishDate nvarchar(20),
#CreateUserId int,
#CreatedDate nvarchar(20),
#ModifiedUserID int,
#ModifiedDate nvarchar(20),
#Is_CommonTask bit
) AS
BEGIN
IF Exists( select null from TblTasks where TaskId=#TaskId)
BEGIN
INSERT TblTasks
VALUES (#ProjectId,#EmployeeId,#TaskName,#Duration_Hrs,
#StartDate,#FinishDate,#CreateUserId,#CreatedDate,
#ModifiedUserID,#ModifiedDate,#Is_CommonTask)
END
ELSE
BEGIN
UPDATE TblTasks SET
StartDate=#StartDate,FinishDate=#FinishDate,
Duration_Hrs=#Duration_Hrs
WHERE TaskId=#TaskId
END
END
GO
First of all, give your input variable TaskID a default value like below, then simply check to see if the variable is NULL, if so, insert a new row
Alter PROCEDURE TaskSave
(
#taskid int = NULL,
#ProjectId int,
#EmployeeId int,
#TaskName nvarchar(50),
#Duration_Hrs int,
#StartDate nvarchar(20),
#FinishDate nvarchar(20),
#CreateUserId int,
#CreatedDate nvarchar(20),
#ModifiedUserID int,
#ModifiedDate nvarchar(20),
#Is_CommonTask bit
) AS
BEGIN
IF #taskid IS NULL
BEGIN
INSERT TblTasks
VALUES (#ProjectId,#EmployeeId,#TaskName,#Duration_Hrs,
#StartDate,#FinishDate,#CreateUserId,#CreatedDate,
#ModifiedUserID,#ModifiedDate,#Is_CommonTask)
END
ELSE
BEGIN
UPDATE TblTasks SET
StartDate=#StartDate,FinishDate=#FinishDate,
Duration_Hrs=#Duration_Hrs
WHERE TaskId=#TaskId
END
END
GO
You are close, check if the record doesn't exist and perform insert, otherwise update. You can also declare the #TaskId parameter as OUTPUT and return it when inserting, using the SCOPE_IDENTITY() function:
ALTER PROCEDURE TaskSave(
#TaskId INT = NULL OUTPUT
, #ProjectId INT
, #EmployeeId INT
, #TaskName NVARCHAR(50)
, #Duration_Hrs INT
, #StartDate NVARCHAR(20)
, #FinishDate NVARCHAR(20)
, #CreateUserId INT
, #CreatedDate NVARCHAR(20)
, #ModifiedUserID INT
, #ModifiedDate NVARCHAR(20)
, #Is_CommonTask BIT
)
AS
BEGIN
IF NOT(EXISTS(SELECT * FROM TblTasks WHERE TaskId = #TaskId))
BEGIN
INSERT INTO TblTasks(
ProjectId
, EmployeeId
, TaskName
, Duration_Hrs
, StartDate
, FinishDate
, CreateUserId
, CreatedDate
, ModifiedUserID
, ModifiedDate
, Is_CommonTask
)
VALUES(
#ProjectId
, #EmployeeId
, #TaskName
, #Duration_Hrs
, #StartDate
, #FinishDate
, #CreateUserId
, #CreatedDate
, #ModifiedUserID
, #ModifiedDate
, #Is_CommonTask
)
SET #TaskId = SCOPE_IDENTITY()
END
ELSE
BEGIN
UPDATE TblTasks SET
StartDate = #StartDate
, FinishDate = #FinishDate
, Duration_Hrs = #Duration_Hrs
WHERE TaskId=#TaskId
END
END
GO
declare #taskid parameter as NULL. the if it is null then insert else update. see below.
Alter PROCEDURE TaskSave
(
#taskid int =NULL,
#ProjectId int,
#EmployeeId int,
#TaskName nvarchar(50),
#Duration_Hrs int,
#StartDate nvarchar(20),
#FinishDate nvarchar(20),
#CreateUserId int,
#CreatedDate nvarchar(20),
#ModifiedUserID int,
#ModifiedDate nvarchar(20),
#Is_CommonTask bit
) AS
BEGIN
if #taskid is null
BEGIN
INSERT TblTasks
VALUES (#ProjectId,#EmployeeId,#TaskName,#Duration_Hrs,
#StartDate,#FinishDate,#CreateUserId,#CreatedDate,
#ModifiedUserID,#ModifiedDate,#Is_CommonTask)
END
ELSE
BEGIN
UPDATE TblTasks SET
StartDate=#StartDate,FinishDate=#FinishDate,
Duration_Hrs=#Duration_Hrs
WHERE TaskId=#taskid
END
END
GO
In cases like these, I used to create a general stored procedure which is capable of inserting, updating and deleting an item. The general pattern looked like this
create procedure Modify_MyTable
#Action char(1),
#Data int,
#PK int output
as
if #Action = 'I' begin -- Insert
insert into MyTable (Data) values (#Data)
set #PK = Scope_Identity()
end
if #Action = 'M' begin -- Modify
update MyTable set Data = #Data where PKID = #PK
end
if #Action = 'D' begin -- Delete
delete MyTable where PKID = #PK
end
It is quite a while ago when I used this but I found it quite handy as I have all the manipulation code in one SP (I could have used three, of course) and could also add logging features and other basic logic in this procedure.
I am not saying that this is still the best method but it should show the basic logic.