I want to save with Stored Procedure. Please check my script first
`USE [Payroll]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[ResignSave]
(
#ResignCode varchar(50),
#Nip Varchar(50),
#Keterangan Varchar(50),
#ResignDate Varchar(50),
#CreatedBy varchar(50),
#CreatedDate date,
#msg varchar(25) = NULL
)
AS
BEGIN
Begin Try
set #ResignCode = (select case
when right(max(ResignCode),7) is null then 'RC0000001'
else ('RC' + RIGHT('0000000' + cast(right(max(ResignCode),7) + 1 as nvarchar),7))
end ResignCode from Resign)
INSERT INTO Resign(ResignCode,Nip, Keterangan, ResignDate, CreatedBy,CreatedDate)
VALUES(#ResignCode,#Nip,#Keterangan, #ResignDate,#CreatedBy,GETDATE())
end try
Begin Catch
Select ERROR_NUMBER() as ErrorNumber, ERROR_MESSAGE() as ErrorMessage
End Catch
End
`
My Stored Procedure working fine. My question is, is there anyway to checking the input if it's exists in my table then set it to my #msg.
You might be looking for below code.
ALTER Procedure [dbo].[ResignSave]
(
#ResignCode varchar(50),
#Nip Varchar(50),
#Keterangan Varchar(50),
#ResignDate Varchar(50),
#CreatedBy varchar(50),
#CreatedDate date,
#msg varchar(25) = NULL
)
AS
BEGIN
Begin Try
if exists (select * from Resign where ResignCode = #ResignCode and Nip = #Nip and ResignDate = #ResignDate) then
BEGIN
set #msg = 'Record already exists'
select #msg AS ProcResult
END
set #ResignCode = (select case
when right(max(ResignCode),7) is null then 'RC0000001'
else ('RC' + RIGHT('0000000' + cast(right(max(ResignCode),7) + 1 as nvarchar),7))
end ResignCode from Resign)
INSERT INTO Resign(ResignCode,Nip, Keterangan, ResignDate, CreatedBy,CreatedDate)
VALUES(#ResignCode,#Nip,#Keterangan, #ResignDate,#CreatedBy,GETDATE())
SELECT 'Insert Successful' AS ProcResult
end try
Begin Catch
Select 'Insert Failed:' + cast(ERROR_NUMBER() as varchar) + ERROR_MESSAGE() AS ProcResult
End Catch
End
If this is what you are looking for, you don't need the #msg parameter. juts execute the procedure and get the returned result set
Related
This is my SP, I am trying to parse this and the error
Incorrect syntax near '$.Role'
was shown.
The JSON is stored in a tables's column. What am I doing wrong?
CREATE PROCEDURE [dbo].[sp_GetKeyPersonRoleMinMax]
#SectionID INT,
#ProposalID INT
AS
SET NOCOUNT ON
Declare #FldKPRoleRequirementsList NVARCHAR(MAX)
Declare #FldName varchar(50)
DEclare #FldIncl varchar(50)
Declare #FldRequired varchar(50)
Declare #FldLabel varchar(max)
Declare #FldList varchar(max)
CREATE Table #RoleMinMaxTemp
(
ID INT IDENTITY(1, 1) ,
Role nvarchar(1000),
MinRoleCount INT,
MaxRoleCount INT
)
Declare Fld_Cursor Cursor For
SELECT FldName, FldIncl, FldRequired, FldLabel,FldList from tblFld where FldParent = 1367 AND FldName like 'FldKPRoleRequirementsList%'
SET NOCOUNT ON
Open Fld_Cursor
WHILE (##Fetch_Status = 0)
BEGIN
if (#FldName = 'FldKPRoleRequirementsList')
BEGIN
SET #FldKPRoleRequirementsList = #FldList
END
FETCH next from Fld_Cursor into #FldName, #FldIncl, #FldRequired, #FldLabel,#FldList
END
Close Fld_Cursor
Deallocate Fld_Cursor
IF(#FldKPRoleRequirementsList IS NOT NULL and Len(#FldKPRoleRequirementsList) >0)
BEGIN
INSERT INTO #RoleMinMaxTemp
SELECT *
FROM OPENJSON(#FldKPRoleRequirementsList,'$.FldRole')
WITH (
Role nvarchar(1000) '$.Role',
MinRoleCount INT '$.MinRoleCount',
MaxRoleCount INT '$.MaxRoleCount'
);
END;
What is the reason for this error? I am using SQL Server 2016.
Try changing you compactibility of SQL SERVER to 130. Your must be below that.
ALTER DATABASE <DatabaseName> SET COMPATIBILITY_LEVEL = 130
Use this script to change it.
I am working with a bank database with two tables i.e [Card] and [Transaction].
I have created a stored procedure login that gets as inputs pin and cardNumber and returns the validity of card in an output parameter. Now, I have created another stored procedure withdraw that gets inputs pin, cardNum, transactionAmount and starts a transaction. I am trying to use p1 procedure to handle the validity part. Here are the 2 procedures
create procedure login
#status int output,
#pin varchar(4),
#cnum varchar(20)
as
begin
if exists (select * from [Card] where PIN = #pin AND cardNum = #cnum)
begin
set #status = 1
end
else
begin
set #status = 0
end
end
alter procedure WithDraw
#pin varchar(4),
#cnum varchar(20),
#trAmount int
as
begin
declare #m int
exec login #pin = N'0234', #cnum = N'2324325423336', #status = #m OUTPUT
if (select #m) = 1
--if exists (select * from [Card] where cardNum = #cnum AND pin = #pin)
--working fine with above statement
begin
if exists (select * from [Card]
where cardNum = #cnum AND pin = #pin AND (balance > #trAmount))
begin
update [Card]
set balance = balance - #trAmount
where cardNum = #cnum AND pin = #pin
declare #maxID int
select #maxID = MAX(transId) from [Transaction]
insert into [Transaction]
values (#maxID + 1, GETDATE(), #cnum, #trAmount, 1)
print 'Transaction successful'
end
else
begin
select #maxID = MAX(transId) from [Transaction]
insert into [Transaction]
values(#maxID + 1, GETDATE(), #cnum, #trAmount, 4)
print 'Transaction unsuccessful! Insufficient balance in card'
end
end
else
begin
print 'login failed'
end
end
exec WithDraw #pin = N'1770', #cnum = N'1324327436569', #trAmount = 50000
However, when I execute withdraw with login procedure inside, login always fails. When i execute without login procedure everything works fine. Any help will be greatly appreciated.
I create a stored procedure and I want to use transaction in this. So how can I use transaction in this stored procedure? Which part will start the transaction because INSERT and UPDATE both are together in this stored procedure.
This is my stored procedure:
ALTER PROCEDURE [dbo].[usp_InsertUpdateADAlertRecipient]
#AD_User_ID int,
#AD_Client_ID int,
#AD_Org_ID int,
#IsActive bit,
#Created datetime,
#Createdby int,
#Updated datetime,
#Updatedby int,
#AD_Alertrecipient_ID int,
#AD_AlertRule_ID int,
#AD_Role_ID int,
#Sendemail bit
AS
SET NOCOUNT ON
IF EXISTS(SELECT [AD_Alertrecipient_ID] FROM [dbo].[AD_AlertRecipient] WHERE [AD_Alertrecipient_ID] = #AD_Alertrecipient_ID)
BEGIN
UPDATE [dbo].[AD_AlertRecipient] SET
[AD_User_ID] = #AD_User_ID,
[AD_Client_ID] = #AD_Client_ID,
[AD_Org_ID] = #AD_Org_ID,
[IsActive] = #IsActive,
[Created] = #Created,
[Createdby] = #Createdby,
[Updated] = #Updated,
[Updatedby] = #Updatedby,
[AD_AlertRule_ID] = #AD_AlertRule_ID,
[AD_Role_ID] = #AD_Role_ID,
[Sendemail] = #Sendemail
WHERE
[AD_Alertrecipient_ID] = #AD_Alertrecipient_ID
select #AD_Alertrecipient_ID
END
ELSE
BEGIN
INSERT INTO [dbo].[AD_AlertRecipient] (
[AD_User_ID],
[AD_Client_ID],
[AD_Org_ID],
[IsActive],
[Created],
[Createdby],
[Updated],
[Updatedby],
--[AD_Alertrecipient_ID],
[AD_AlertRule_ID],
[AD_Role_ID],
[Sendemail]
) VALUES (
#AD_User_ID,
#AD_Client_ID,
#AD_Org_ID,
#IsActive,
#Created,
#Createdby,
#Updated,
#Updatedby,
--#AD_Alertrecipient_ID,
#AD_AlertRule_ID,
#AD_Role_ID,
#Sendemail
)
SELECT SCOPE_IDENTITY()
END
Thanks and waiting for your reply .
I have written the following stored procedure which in HeidiSQL is giving me an Error 1064 at the line starting with SET pay_ref = SELECT CONCAT('KOS' ...
Let me firstly explain what's going on with this procedure. I have a table gamers with a BIGINT primary key with auto_increment. This proc is supposed to:
Take in some params from the user
Check if the user already exists in the db according to his/her email address, and spits back the word "DUPLICATE" if a reord does exist
Else it does the insert as normal
Then it reads in the ID of the new record created and converts it to a varchar, pads it with leading zeros and then gets concatenated with some other strings
This new string (which should read for example KOS00001ABCDEF) then gets updated to the pay_refcode field >>> this is how we have settled on generating a unique payment reference for the user
If all works out well it updates retval with the newly generated reference code to be read by PHP script.
DELIMITER //
CREATE PROCEDURE `InsertGamer` (
IN p_fname VARCHAR(30),
IN p_lname VARCHAR(30),
IN p_email VARCHAR(255),
IN p_favgame VARCHAR(60),
IN p_pay_suffix VARCHAR(6),
OUT retval VARCHAR(14)
)
BEGIN
DECLARE last_id BIGINT;
DECLARE pay_ref VARCHAR(14);
IF (EXISTS(SELECT * FROM gamers WHERE (email = p_email))) THEN
SET retval = 'DUPLICATE';
ELSE
INSERT INTO gamers (fname, lname, email, favgame, pay_refcode)
VALUES (p_fname, p_lname, p_email, p_favgame, NULL);
SET last_id = LAST_INSERT_ID();
SET pay_ref = SELECT CONCAT('KOS', (SELECT LPAD(CONVERT(last_id, VARCHAR(5)),5,'0')), p_pay_suffix);
UPDATE gamers
SET pay_refcode = pay_ref
WHERE application_id = last_id;
SET retval = pay_ref;
END IF;
END //
I cannot for the life of me figure out what the problem is and would sincerely appreciate any help from you. Thank you very much in advance!
You just need to remove the SELECT keyword from line which you set the value for pay_ref.
SET pay_ref = CONCAT('KOS', LPAD(CONVERT(last_id, CHAR(5)),5,'0'), p_pay_suffix);
full code:
DELIMITER //
CREATE PROCEDURE `InsertGamer` (
IN p_fname VARCHAR(30),
IN p_lname VARCHAR(30),
IN p_email VARCHAR(255),
IN p_favgame VARCHAR(60),
IN p_pay_suffix VARCHAR(6),
OUT retval VARCHAR(14)
)
BEGIN
DECLARE last_id BIGINT;
DECLARE pay_ref VARCHAR(14);
SET #count := (SELECT COUNT(*) FROM gamers WHERE email = p_email)
IF (#count > 0) THEN
SET retval = 'DUPLICATE';
ELSE
INSERT INTO gamers (fname, lname, email, favgame, pay_refcode)
VALUES (p_fname, p_lname, p_email, p_favgame, NULL);
SET last_id = LAST_INSERT_ID();
SET pay_ref = CONCAT('KOS', LPAD(CONVERT(last_id, CHAR(5)),5,'0'), p_pay_suffix);
UPDATE gamers
SET pay_refcode = pay_ref
WHERE application_id = last_id;
SET retval = pay_ref;
END IF;
END //
DELIMITER ;
I have recursive stored procedure on SQL Server. I'm using Linq-to-SQL generated classes, and drag & drop procedure to this class.
Other procedures are working fine, but this procedures fails with exception:
"System.Void" not allowed return
type. invalid operation exception
Stored procedure:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[delListEnterprise]
#pin_list_enterprise_id numeric(38,0),
#cCriteria varchar(250) = null,
#iLevel int = 0
AS
begin
set nocount on
declare
#cSQL varchar(255),
#cChildCriteria varchar(255),
#iLevelNew int
IF #iLevel = 0
BEGIN
set #cCriteria='parent_list_enterprise_id='+cast(#pin_list_enterprise_id as varchar(30));
delete from list_enterprise where list_enterprise_id=#pin_list_enterprise_id;
Create Table #tblCascadeDelete (CallLevel int NOT NULL, PKValue int NOT NULL)
END
SET #cSQL = 'INSERT INTO #tblCascadeDelete ( CallLevel, PKValue ) SELECT ' + Convert(varchar(3), #iLevel) + ' As CallLevel, list_enterprise_id As PKValue FROM list_enterprise WHERE ' + #cCriteria
EXEC (#cSQL)
IF ##RowCount > 0
BEGIN
SET #cChildCriteria = '[parent_list_enterprise_id] IN (SELECT [PKValue] FROM #tblCascadeDelete Where [CallLevel] = ' + Convert(varchar(3), #iLevel) + ')'
SET #iLevelNew = #iLevel + 1
EXEC delListEnterprise null,#cChildCriteria, #iLevelNew
END
SET #cSQL = 'DELETE FROM list_enterprise WHERE ' + #cCriteria
EXEC (#cSQL)
IF #iLevel = 0
BEGIN
Drop Table #tblCascadeDelete
END
ELSE
DELETE FROM #tblCascadeDelete WHERE CallLevel = #iLevel
end
It works, if I run it in SQL Server Management Studio.
Just add a return/output parameter to the stored proc. I suspect this is a Linq2SQL limitation (or no-one thought of it).