Stored Procedure OutPut Parameters - sql

i need to write a stored procedure which will return a string.logic is
when user try to insert a new record i need to check whether that record already exist.if exist need to return msg "Record exist" else return "Inserted"
following is what i have done for the moment and i'm stuck here.can some one help me to complete the procedure
CREATE PROCEDURE [dbo].[spInsetPurpose]
#Purpose VARCHAR(500),
#Type VARCHAR(6),
#Result VARCHAR(10)= NULL OUTPUT
AS
BEGIN
Declare #Position VARCHAR(20)
DECLARE #TempTable TABLE (Purpose VARCHAR(500))
INSERT INTO #TempTable
SELECT Purpose FROM tblPurpose WHERE Purpose=#Purpose
INSERT INTO tblPurpose(Purpose,[Type]) VALUES(#Purpose,#Type)
END

To check if the row already exists you can do
If Exists (Select Top 1 1 from tblPurpose where Purpose = #Purpose and [Type] = #Type)
Begin
Insert Into tblPurpose
(Purpose, [Type])
Select
#Purpose, #Type
SET #Result = 'Inserted'
End
Else
Begin
SET #Result = 'Record exists'
End

Related

SQL with input condition

I have a customer table-firstname,lastname,gender,salary. I am creating a stored procedure with 5 input parameters: #FN, #LN, #GNDR, #SLRY and #TYPE.
Now, if #type=0 and #FN='SAM' - then,
it should insert a new record in the table, if 'SAM' is already existing in the table.
if #type=1 and #FN='SAM' - then,
it should delete a record from the table, if 'SAM' is already existing in the table.
if #type=2 and #FN='SAM' - then,
it should update a record in the table if 'SAM' is already existing in the table.
Please help me in creating a query for the above condition.
Please check by solution .
Please create different case in SQL Server .
CREATE PROCEDURE Insertcustomer (
#FN VARCHAR(30),
#LN VARCHAR(30),
#GNDR VARCHAR(30),
#SLRY DECIMAL(18,3) ,
#TYPE INT )
As
BEGIN
IF #type=0 AND #FN='SAM'
BEGIN
Insert into customer(firstname,lastname,gender,salary)values(#FN,
#LN,#GNDR,#SLRY,#TYPE)
END
IF #type=1 AND #FN='SAM'
BEGIN
Delete from customer where firstname= #FN
END
IF #type=2 AND #FN='SAM'
BEGIN
update customer set
firstname=#FN,lastname=#LN,gender=#GNDR,salary=#SLRY where
firstname= #FN
END
END
It will be work for you .
Thanks .
This elaborates on JaydibJ's PROC
CREATE PROCEDURE ProcedureName (#FN VARCHAR(30), #LN VARCHAR(30), #GNDR VARCHAR(30), #SLRY DECIMAL(18,3) , #TYPE INT )
As
BEGIN
IF #FN = 'SAM' AND (SELECT COUNT(*) FROM YourTable WHERE SomeColumn = 'SAM') > 0) --Only check this condition once
BEGIN
IF #TYPE=0
BEGIN
INSERT 'SOME VALUE' INTO YourTable WHERE <some condition>
END
IF #TYPE=1
BEGIN
DELETE FROM YourTable WHERE <some condition>
END
IF #TYPE=1
BEGIN
UPDATE YourTable
SET SomeColumn = 'SomeValue' WHERE <some condition>
END
END
ELSE
SELECT 'SAM was not supplied in the parameters or did not exist in table' -- or some logic
END
As per given requirement below stored procedure will help you
CREATE PROCEDURE ProcedureName (
#FN VARCHAR(30), #LN VARCHAR(30), #GNDR VARCHAR(30), #SLRY DECIMAL(18,3) , #TYPE INT )
As
BEGIN
IF #type=0 AND #FN='SAM'
BEGIN
--INSERT Command here
END
IF #type=1 AND #FN='SAM'
BEGIN
--DELETE Command here
END
IF #type=2 AND #FN='SAM'
BEGIN
--UPDATE Command here
END
END

SQL Server stored procedure: verify CRUD operation success/failure using output variable

I am trying to create a SQL Server stored procedure to handle updates to a table using some dynamic SQL. The table name required for the update is stored in a table that correlates a table id to a category id. Once the table name is retrieved and the table id is not null, I update the table using a dynamic SQL query as shown below:
CREATE PROCEDURE [dbo].[SP_EBS_CustomForms_SetCategoryData]
(#flag int output,
#cat_id int,
#sort int,
#value varchar(50),
#active int,
#enum int)
AS
BEGIN
DECLARE #tbl as varchar(50)
DECLARE #tbl_id as int
DECLARE #sql nvarchar(max)
BEGIN TRY
SET #tbl_id = (SELECT [tbl_id]
FROM [demodata].[dbo].[ebscustomforms_cattable]
WHERE cat_id = #cat_id)
IF #tbl_id IS NOT NULL
BEGIN
SET #tbl = (SELECT table_name
FROM ebscustomforms_enumtable
WHERE tbl_id = #tbl_id)
SET #sql = 'UPDATE ' + #tbl + ' SET [sort_order] = #sort, [value] = #value, [active] = #active WHERE [enum_id] = #enum'
EXECUTE sp_executesql #sql, N'#sort int, #value varchar(50), #active int, #enum int', #sort, #value, #active, #enum
SET #flag = 0
RETURN #flag
END
END TRY
BEGIN CATCH
IF ##ERROR <> 0
BEGIN
SET #flag = 1;
RETURN #flag
END
END CATCH
END
I want this stored procedure to return an int value indicating whether the stored procedure was successful (0) or failed (1) updating the table.
Points of error are as follows:
#tbl_id variable is null
#tbl is either null or an empty varchar
The table to be updated does not have a record where [enum_id] = #enum
I have noticed that when I try to update a record that does not exist, the procedure seems to return as successful i.e. #flag = 0. However, I would imagine that an error should be thrown because the record does not exist.

Stored procedure unsure syntax

I am trying to create a stored procedure that will determine if my customerid exists if it exists then my other parameter foundcustomer will be assigned to found otherwise not found. I am unsure how to assign found please help
here is what i tried
CREATE PROCEDURE procedure4
-- Add the parameters for the stored procedure here
#FoundCustomer varchar(10) = null,
#Customerid varchar (5) = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
if Not(#Customerid is null)
SELECT customerid
from customers
where customerid = #Customerid
END
GO
Gordon is right, it sounds like you may want a function but if it has to be a stored procedure you can follow this example.
CREATE PROCEDURE procedure4
#Customerid varchar(5) = null
AS
BEGIN
SET NOCOUNT ON;
DECLARE #FoundCustomer varchar(10) = ''
IF #FoundCustomer is not null
BEGIN
IF (SELECT COUNT(1) FROM customers WHERE customerid = #customerid) > 0
SET #FoundCustomer = 'Found'
ELSE
SET #FoundCustomer = 'Not Found'
END
SELECT #FoundCustomer
END

Return one OUTPUT result from MERGE query

I have a merge query which updates or inserts if no records found. In my results, I have a problem when the record does not exist and it get inserted. The query returns BOTH 'Updated' (as empty) and 'Inserted' (with the proper value).
Any ideas how to avoid return the empty 'Updated' when there are no updates?
ALTER PROCEDURE [dbo].[spInsOrUpdApplicant]
-- Add the parameters for the stored procedure here
#Name nvarchar(50),
#Surname nvarchar(50),
#Position nvarchar(50),
#NationalID int,
#ApplicantID int
AS
BEGIN
SET NOCOUNT ON;
-- Update the row if it exists.
UPDATE tbApplicant
SET Name = #Name, Surname = #Surname, Position = #Position, NationalID = #NationalID
OUTPUT INSERTED.ApplicantID AS 'Result'
WHERE ApplicantID = #ApplicantID;
-- Insert the row if the UPDATE statement failed.
IF (##ROWCOUNT = 0 )
BEGIN
INSERT INTO tbApplicant (Name, Surname, Position, NationalID)
OUTPUT INSERTED.ApplicantID AS 'Result'
VALUES (#Name, #Surname, #Position, #NationalID)
END
END;
It seems that the 'output' always fires even if no actual rows were updated. You can see the same behavior in triggers. You might want to consider doing the following:
ALTER PROCEDURE [dbo].[spInsOrUpdApplicant]
-- Add the parameters for the stored procedure here
#Name nvarchar(50),
#Surname nvarchar(50),
#Position nvarchar(50),
#NationalID int,
#ApplicantID int
AS
BEGIN
SET NOCOUNT ON;
-- Check if the row exists.
IF EXISTS (SELECT 1 FROM tbApplicant WHERE ApplicantID = #ApplicantID) BEGIN
-- update if the row exists.
UPDATE tbApplicant
SET Name = #Name, Surname = #Surname, Position = #Position, NationalID = #NationalID
OUTPUT INSERTED.ApplicantID AS 'Result'
WHERE ApplicantID = #ApplicantID;
END
ELSE BEGIN
-- Else Insert.
INSERT INTO tbApplicant (Name, Surname, Position, NationalID)
OUTPUT INSERTED.ApplicantID AS 'Result'
VALUES (#Name, #Surname, #Position, #NationalID)
END
END;
I do something very similar.
Inside my stored procedure, I have this:
DECLARE #mergeResults TABLE (mergeAction varchar(10), tableName varchar(50));
OUTPUT $action, 'Table Name' INTO #mergeResults;
Can you insert into the table variable and then decide how you want to move the data based on what you see?
You mentioned you have a merge query but you aren't using a merge - you're using more of an "upsert".
Merge T-SQL: http://msdn.microsoft.com/en-us/library/bb510625.aspx

How to update SQL field using function and stored procedure?

What I want to do is to update column (NewID) in my table (SampleTable) with the following code, but it's not working.. can somebody help me please? Whats wrong with it?
I have the table 'SampleTable' wich has the fields 'NewID' and 'OldID'.
UPDATE SampleTable SET NewID = dbo.fn_DoStuff(OldID) <-- Not working
My function:
ALTER FUNCTION [dbo].[fn_DoStuff]
(
#int oldid
)
RETURNS int
AS
BEGIN
DECLARE #returnValue int
EXEC #returnValue = dbo.spc_DoStuff #oldid
RETURN #returnValue
END
My stored procedure:
SampleTable1 has the columns ID, SomeColName.
ALTER PROCEDURE [dbo].[spc_GeraAtriðisorðalistaÚrAtriðisorði]
(
#oldid int
)
AS
BEGIN
DECLARE #returnValue int
INSERT INTO SampleTable1 (SomeColName) VALUES (null)
SET #returnValue = ##IDENTITY
INSERT INTO SampleTable2 (SomeColName1, SomeColName2) VALUES (#returnValue, #oldid)
SELECT #returnValue AS RetVal
END
You have 2 problems, the first is you cannot call a stored procedure inside a function, nor can you perform your insert within a function.
The second problem is that even if you could call a stored procedure inside a function, you are not returning the value from the procedure correctly. You would need something like:
CREATE TABLE dbo.T (ID INT IDENTITY, Filler CHAR(10));
GO
CREATE PROCEDURE dbo.Test
AS
DECLARE #i INT;
INSERT dbo.T (Filler) VALUES (NULL);
RETURN SCOPE_IDENTITY();
GO
Note the use of the RETURN statement, if you don't use this the default return value is 0
Then you can use:
DECLARE #i INT;
EXECUTE #i = dbo.Test;
SELECT ReturnVal = #i;
*Note, I have replaced ##IDENTITY with SCOPE_IDENTITY(), ##IDENTITY is rarely the correct function to use*
Example on SQL Fiddle
With your solution GarethD I could still not call the function like I wanted to
UPDATE SampleTable SET NewID = dbo.fn_DoStuff(OldID).
Your code helped me though to start thinking another way. Now I'm using a cursor and a while loop and it works perfectly. See my solution below:
DECLARE #OldID AS INT
DECLARE Upd_CURSOR FOR
SELECT OldID
FROM dbo.SampleTable
WHERE OldID is not null
FOR UPDATE OF NewID
OPEN Upd_CURSOR;
FETCH NEXT FROM Upd_CURSOR INTO #OldID
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #returnValue int;
INSERT INTO SampleTable1 (SomeColName) VALUES (null);
SET #returnValue = SCOPE_IDENTITY();
INSERT INTO SampleTable2 (SomeColName1, SomeColName2) VALUES (#returnValue, #OldID)
UPDATE dbo.SampleTable SET NewID = #returnValue WHERE CURRENT OF Upd_CURSOR;
FETCH NEXT FROM Upd_CURSOR INTO #OldID;
END;
CLOSE Upd_CURSOR;
DEALLOCATE Upd_CURSOR;
GO