ALTER PROCEDURE [dbo].[STL_ADDNEWROLE](#ROLENAME VARCHAR(100), #STATUS BIT)
AS
BEGIN
SET NOCOUNT ON;
IF(#ROLENAME IS NULL OR #STATUS IS NULL)
BEGIN
RETURN 0
END
ELSE
BEGIN
IF EXISTS (SELECT [RoleName], [Status] FROM ST_Roles
WHERE [RoleName] = #ROLENAME)
BEGIN
RETURN 0
END
ELSE IF(#ROLENAME IS NOT NULL)
BEGIN
INSERT INTO ST_Roles ([RoleName], [Status]) VALUES(#ROLENAME, #STATUS)
RETURN 1
END
END
END
The above is my stored proc. When NULL values are passed it should return 0. Even when 1 value is passed and another value is not passed it should return 0 instead of inserting the record.
Any help is really appreciated.
Before you describe your problem, I'll just guess. I suppose the problem is in default parameters. Maybe you just don't pass parameters or you pass empty string, so try this way
ALTER PROCEDURE [dbo].[STL_ADDNEWROLE](
#ROLENAME VARCHAR(100) = NULL,
#STATUS BIT = NULL)
AS
BEGIN
SET NOCOUNT ON;
IF(ISNULL(#ROLENAME, '') = '' OR #STATUS IS NULL)
BEGIN
RETURN 0
END
ELSE
BEGIN
IF EXISTS (SELECT [RoleName],[Status] from ST_Roles where [RoleName] = #ROLENAME)
BEGIN
RETURN 0
END
ELSE IF(#ROLENAME IS NOT NULL)
BEGIN
INSERT INTO ST_Roles ([RoleName],[Status]) VALUES(#ROLENAME,#STATUS)
RETURN 1
END
END
END
Related
I have an SP which brings a table with some fields and subtracts the results to another table, I tried to do this as a function but as you know you can not use DML sentences in a function so I created this SP:
CREATE OR ALTER PROCEDURE SP_Integraciones_AsignarLotesLineas
#Cantidad numeric, #producto nvarchar(max), #bodega nvarchar(max)
AS
BEGIN
BEGIN TRY
BEGIN TRAN
DECLARE #temp as table(idLoteT nvarchar(max), CantidadT numeric, FechaT date)
DECLARE #loteAc nvarchar(Max), #CantidadAc numeric, #restante numeric , #Cont numeric, #fechaAc date, #resultado nvarchar(max)
SET #Cont = #Cantidad
DECLARE CursoIns CURSOR SCROLL
FOR SELECT IdLote, CONVERT(NUMERIC,cantidad), Fecha
FROM tblintegraciones_lotes
WHERE idproducto = #producto
AND Bodega = #bodega
AND cantidad > '0.0'
ORDER BY fecha ASC
OPEN CursoIns
FETCH CursoIns INTO #loteAc, #CantidadAc, #fechaAc
WHILE( #Cont > 0 AND ##FETCH_STATUS = 0 )
BEGIN
IF( #CantidadAc >= #Cont )
BEGIN
SET #restante = #CantidadAc- #Cont
INSERT INTO #temp(
idLoteT, CantidadT, FechaT
)VALUES(
#loteAc, #Cont, #fechaAc
)
UPDATE tblintegraciones_lotes SET Cantidad = #restante WHERE idProducto = #producto AND IdLote = #loteAc
SET #Cont = #cont - #CantidadAc
END
ELSE
BEGIN
SET #Cont = #Cont - #CantidadAc
SET #restante = #Cont - #CantidadAc
INSERT INTO #temp(
idLoteT, CantidadT, FechaT
)VALUES(
#loteAc, #CantidadAc, #fechaAc
)
UPDATE tblintegraciones_lotes SET Cantidad = 0 WHERE idProducto = #producto AND IdLote = #loteAc
END
FETCH CursoIns INTO #loteAc, #CantidadAc, #fechaAc
END
CLOSE CursoIns;
DEALLOCATE CursoIns;
SELECT * FROM #temp
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK
DECLARE #DescripcionError AS nvarchar(max)
SET #DescripcionError = ERROR_MESSAGE()
RAISERROR (#DescripcionError, 18, 1, 'Inventario - lotes - Integraciones', 5)
END CATCH
END
GO
but the problem is that I must run this in a select since I need that query parcing to JSON, so there should be 2 solutions:
Execute this SP in a select sentence
Create some function that calls the SP.
Can you help me how can I execute this SP in a function or find the best soluction?
Here the Query that I need execute this:
(SELECT CASE
WHEN MFAC.codigo IN ('ME-14009',
'ME-14010',
'ME-14011') THEN 'IMP-BOLSAP'
ELSE MFAC.codigo
END AS ItemCode,
REPLACE(MFAC.cantidad, ',', '.') AS Quantity,
CASE WHEN MFAC.codigo LIKE '%PV%' THEN MFAC.valor ELSE null END as Price,
REPLACE(MFAC.descuento, ',', '.') AS DiscountPercent,
CASE
WHEN MFAC.codbodega = 'PV-PER' THEN 'PV-DQU'
ELSE MFAC.codbodega
END AS WarehouseCode,
#OcrCode3 AS CostingCode3,
#OcrCode3 AS COGSCostingCode3
FOR JSON PATH
) DocumentLines
This stored procedure is supposed to update the complaint table in the database and return 0 when it is successful. When I input valid values it correctly updates the table and returns 0. But when I input invalid values it returns 0 even there is no update.
CREATE PROCEDURE updateComplaintStatusDetails
(#_ID INT,
#_subID INT,
#_Status varchar(10))
AS
BEGIN TRANSACTION
IF #_Status = 'InProgress'
BEGIN
UPDATE COMPLAINT
SET status = (SELECT statusID FROM COMPLAINT_STATUS WHERE statusName = #_Status),
wipStartDate = GETDATE()
WHERE complaintID = #_ID AND subComplaintID = #_subID
END
ELSE IF #_Status = 'Completed'
BEGIN
UPDATE COMPLAINT
SET status = (SELECT statusID FROM COMPLAINT_STATUS WHERE statusName = #_Status),
finishedDate = GETDATE()
WHERE complaintID = #_ID AND subComplaintID = #_subID
END
ELSE
BEGIN
UPDATE COMPLAINT
SET status = (SELECT statusID FROM COMPLAINT_STATUS WHERE statusName = #_Status)
WHERE complaintID = #_ID AND subComplaintID = #_subID
end
IF ##ROWCOUNT = 0
GOTO errorHandler;
COMMIT TRANSACTION;
RETURN 0;
errorHandler:
ROLLBACK TRANSACTION
RETURN -1;
GO
I have had problems with ##ROWCOUNT in the past. I bet you if you return the ##ROWCOUNT value you will find that its always the same value.
It is a well know phenomena with the ##ROWCOUNT system variable. It resets its value.
Please try the following:
...
DECLARE #counter INT;
SET #counter = ##ROWCOUNT;
IF #counter = 0
...
I have a scenario where I need to run a stored procedure individually as well as I need to call from some other stored procedure.
Let me present the scenario: I have 3 stored procedures in sequential call from another one. Like 1st stored procedure is getting called from the application when some raw financial data is being imported; 2nd stored procedure is getting called from 1st stored procedure and in 2nd stored procedure, there is a While loop in which my 3rd stored procedure is getting called.
I am posting here 2nd and 3rd stored procedure code here:
2ND stored procedure code:
If #loopCount > 0
Begin
While(#i <= #loopCount)
Begin
Select #RecoString = '',
#CompanyId = 0,
#UserId = 0
Select #RecoString = MainRecord,
#CompanyId = CompanyId,
#UserId = UsersId
From #RecoData With (Nolock)
Where Id = #i
Order By Id
/* 3rd stored procedure is getting called - IF NO INSERT Statement */
----Exec USP_Temp #IsReco = 1,#ReconcileBy = 'system',#UserCompanyId = #UserCompanyId,#UserId = #UserId,#finalCollection = #RecoString
/* 3rd stored procedure is NOT getting called - IF INSERT Statement */
Insert Into dbo.ReconcileInsertUpdateLog(TransferDetailId,Msg,ReconcilationId,IsFutureTransferReconciled)
Exec dbo.USP_Temp #IsReco = 1, #ReconcileBy = 'system', #CompanyId = #CompanyId, #UserId = #UserId, #finalCollection = #RecoString, #isAutoReconcile = 0
Set #i = #i + 1
End
End
3RD stored procedure code:
ALTER PROCEDURE dbo.USP_Temp
#IsReco Bit
,#ReconcileBy Nvarchar(250)
,#UserCompanyId int
,#UserId int
,#finalCollection Nvarchar(Max) = ''
,#isAutoReconcile Bit = 0
AS
BEGIN
Set Nocount On;
Declare #TransName Varchar(100)
Select #TransName = 'USP_Temp'
Begin Try
Begin Transaction #TransName
Declare #Msg Nvarchar(Max) = ''
,#ParentReconcilationId Int = 0 -- 07.25.2019
,#IsFutureTransferReconciled Int = 0 -- 07.25.2019
------------------------------------------------------------
-- Return result
------------------------------------------------------------
Insert Into dbo.TempReco(Comments)
Select 'Reached to USP_Temp 1 step ahead of Return final Result'
Select 1 As TransferDetailId
,#Msg As Msg
,#ParentReconcilationId As ReconcilationId -- 07.25.2019
,#IsFutureTransferReconciled As IsFutureTransferReconciled -- 07.25.2019
Commit Transaction #TransName
GoTo EndLevel
End Try
Begin Catch
Set #Msg = Error_Message()
GoTo Error
End Catch
Error:
BEGIN
Insert Into dbo.TempReco(Comments) Select 'Reached to USP_Temp - Error Block'
Rollback Transaction #TransName
Select 0 As TransferDetailId
,#Msg As Msg
,0 As ReconcilationId -- 07.25.2019
,0 As IsFutureTransferReconciled -- 07.25.2019
END
EndLevel:
END
GO
Look at the 2nd stored procedure code, I have commented the code which is working if no insert into statement prior to Exec SPName and when calling stored procedure along with insert into SomeTable prior statement then stored procedure is not getting called. Does anyone have some idea on this?
I want to modify the Stored Procedure below.
#UserID INT
#Unlock VARCHAR(4)
AS
SET NOCOUNT ON
IF NOT EXISTS (SELECT * FROM dbo.tblUnlockCode WHERE iUserID = #UserID)
BEGIN
IF ISNUMERIC(#Unlock) = 1
BEGIN
INSERT dbo.tblUnlockCode (iUserID, sUnlockCode) VALUES (#UserID, #Unlock)
END
I would actually like to add to it, to where if the iUserID exists Update the #Unlock to the new Pin, and if the iUserID exists on the table but the #Unlock gets erased on the textfield(in access) it gets removed from the Table. I only want to store the iUserIDs that 4 digit pins. How could I do that?
P.S. on access I am checking if the pin is 4 digits.
Try this (I also recommend adding error handling if you have none):
#UserID INT
#Unlock VARCHAR(4)
AS
SET NOCOUNT ON
IF NOT EXISTS (SELECT * FROM dbo.tblUnlockCode WHERE iUserID = #UserID)
BEGIN
IF ISNUMERIC(#Unlock) = 1
BEGIN
INSERT dbo.tblUnlockCode (iUserID, sUnlockCode) VALUES (#UserID, #Unlock)
END
END
ELSE
BEGIN
IF ISNUMERIC(#Unlock) = 1
BEGIN
UPDATE dbo.tblUnlockCode set sUnlockCode=#Unlock WHERE iUserID= #UserID
END
ELSE --Assuming you want to clear the record if unlock code is empty
BEGIN
DELETE dbo.tblUnlockCode WHERE iUserID= #UserID
END
END
I have this store procedure and I lets assume the user want to update some fields not all of it, what should I add on the update section
CREATE PROCEDURE [dbo].[helpChainAllCRUD]
#action char(1),
#lineId char(2),
#lineShift smallint = NULL,
#sequence smallint = NULL,
#Role VARCHAR(32) = NULL,
#radioChannel VARCHAR(16)= NULL,
#officePhone VARCHAR(16)= NULL,
#cellPhone VARCHAR(16)= NULL
as
IF(#action = 'I')
BEGIN TRY
BEGIN TRAN
INSERT INTO [dbo].[tbl_helpChain] (lineId,lineShift,sequence,Role,radioChannel,officePhone,cellPhone)
VALUES (#lineId ,#lineShift,#sequence,#Role,#radioChannel,#officePhone,#cellPhone)
COMMIT
END TRY
BEGIN CATCH
IF ##TRANCOUNT >0
ROLLBACK
END CATCH
IF(#action = 'U')
BEGIN TRY
BEGIN TRAN
UPDATE [dbo].[tbl_helpChain] SET lineShift=#lineShift,sequence=#sequence,Role=#Role,radioChannel=#radioChannel,officePhone=#officePhone,cellPhone=#cellPhone WHERE lineId=#lineId
COMMIT
END TRY
BEGIN CATCH
IF ##TRANCOUNT >0
ROLLBACK
END CATCH
IF(#action = 'D')
BEGIN TRY
BEGIN TRAN
Delete from [dbo].[tbl_helpChain] WHERE lineId=#lineId
COMMIT
END TRY
BEGIN CATCH
IF ##TRANCOUNT >0
ROLLBACK
END CATCH
IF(#action = 'S')
Begin
select lineId,lineShift,sequence,Role,radioChannel,officePhone,cellPhone from [dbo].[tbl_helpChain]
end
GO
I'm sure there are much better solutions, but a quick and easy solution might be to use very ugly dynamic SQL
DECLARE #QueryText nvarchar(max) = 'UPDATE [dbo].[tbl_helpChain] SET '
IF #radioChannel<> NULL
#QueryText = #QueryText + 'RadioChannel=#radioChannel'
EXECUTE SP_EXECUTESQL #QueryText
If i.e. null means don't update you could simply write
SET lineShift = COALESCE(#lineShift,lineShift), ...
or you take another special value and a case-expression
SET lineShift = CASE WHEN #lineShift = -1 then lineShift else #lineShift end,
or you give extra boolean parameters for each column for use in the case-expression
UPDATE helpChain
SET
fullName = ISNULL(#fullName,fullName),
lineShift = ISNULL(#lineShift,lineShift),
sequence = ISNULL(#sequence,sequence),
Role = ISNULL(#Role,Role),
radioChannel = ISNULL(#radioChannel,radioChannel),
officePhone = ISNULL(#officePhone,officePhone),
cellPhone = ISNULL(#cellPhone,cellPhone)
WHERE lineId = #lineId