SQL SERVER: Altering service broker stored procedures - sql

I cannot alter the service broker stored procedure, when I update the stored procedure it does not show any error and successfully gets updated but the changes does not come into affect.
Is it because I need to stop the queue of the service broker on both databases before the changes could come into affect?
Note: the service broker stored procedures produce and read xmls.
INCLUDING THE STORE PROCEDURE
ALTER PROCEDURE [dbo].[ServiceBroker_AtTarget_FromSLICJobEstimateDetailsNewLineAddedBySupplier]
#XML XML(SLICMessageSchema)
AS
BEGIN
-- extract data :
DECLARE
#LogNo INT,
#QuoteReference INT,
#JobEstimatesDetailID INT,
#UserName NVARCHAR(50),
#Description NVARCHAR(MAX),
#UnitValue DECIMAL(18,2),
#Quantity DECIMAL(18,2),
#LineTotal DECIMAL(18,2),
#QuoteTotal DECIMAL(18,2),
#tsCreated DATETIME
SELECT #QuoteReference = #XML.value('data(//FromSLIC/FromSLICJobEstimateDetailsNewLineAddedBySupplier/#QuoteReference)[1]', 'int'),
#JobEstimatesDetailID = #XML.value('data(//FromSLIC/FromSLICJobEstimateDetailsNewLineAddedBySupplier/#JobEstimatesDetailID)[1]', 'int'),
#UserName = #XML.value('data(//FromSLIC/FromSLICJobEstimateDetailsNewLineAddedBySupplier/#UserName)[1]', 'nvarchar(50)'),
#Description = #XML.value('data(//FromSLIC/FromSLICJobEstimateDetailsNewLineAddedBySupplier/#Description)[1]', 'nvarchar(max)'),
#UnitValue = #XML.value('data(//FromSLIC/FromSLICJobEstimateDetailsNewLineAddedBySupplier/#UnitValue)[1]', 'decimal(18,2)'),
#Quantity = #XML.value('data(//FromSLIC/FromSLICJobEstimateDetailsNewLineAddedBySupplier/#Quantity)[1]', 'decimal(18,2)'),
#tsCreated = #XML.value('data(//FromSLIC/FromSLICJobEstimateDetailsNewLineAddedBySupplier/#tsCreated)[1]', 'datetime')
SET #LogNo = (SELECT mlq.logno FROM fsgmgtservices.dbo.maintlogquotes mlq WHERE mlq.quoteno = #QuoteReference)
INSERT INTO fsgcentraldata.dbo.[tblSLICGeneratedEvents]
(EventNameID, tsCreated, CreatedBy, IsAcknowledged, JobNumber, ContractorID)
SELECT 9, #tsCreated, #UserName, 0, #LogNo, je.contractorid
FROM [slic3.0].dbo.JobEstimates je WHERE je.legacyreference = CAST(#quotereference AS varchar(50))
SET #LineTotal = (#UnitValue * #Quantity) // IF I CHANGE IT TO ((#UnitValue * 2)) FOR EXMPL
INSERT INTO fsgmgtservices.dbo.maintlogquotedetails
(quoteno, details, quantity, rate, amount, [date], slicreference)
SELECT #QuoteReference, #description, #quantity, #UnitValue, #LineTotal, #tscreated, #JobEstimatesDetailID
SET #QuoteTotal = (SELECT SUM(mlqd.amount) FROM fsgmgtservices.dbo.maintlogquotedetails mlqd
WHERE mlqd.quoteno = #QuoteReference)
UPDATE fsgmgtservices.dbo.maintlogquotes SET amount = #QuoteTotal WHERE quoteno = #QuoteReference
INSERT INTO [fsgmgtservices].[dbo].maintlognotes
(logno, [date], [user], [note], transferredfromslic)
SELECT #LogNo, #tsCreated, #UserName, 'Quote ' + CAST(#QuoteReference AS varchar(20)) + ', new lines added by supplier in SLIC By ' + #UserName , 0
END

Changing an activated stored procedure does not kill any running instance. Most likely your old code is still running in a loop and will continue to run until it exits the loop or you kill it.

Related

Obtain a repeated data and send SQL mail

Good day I have a table called Ticket which has several tickets registered, each one has a status:
1 = Accepted,2 = Assigned,3 = At ​​attention,4 = Attended,5 = Agree.
I want to perform a stored procedure in which I only send mail to the tickets that are in state 4, that is, my ticket has status 4, it is activated exec sp_sendmail .
Then I will use it as a Job every 30 minutes, check to see if it is still in that state and if it is in state 4 it sends again mail, once it changes state 4 to 5 it will not send anything and it will be closed.
Something like this, that loops through the list of tickets and sends an email. Couple notes, though: first, if you try to send too many at once, your email provider may start dropping them, so maybe put in a {pre}WAITFOR DELAY '00:00:02'{pre} delay between messages. Also, instead of sending one email per ticket, you can look into the query options in sp_send_dbmail: you can email a single list of all currently-4 tickets. It just depends on your needs.
CREATE PROCEDURE dbo.SendTicketAttendedEmails
AS
BEGIN
DECLARE #MailList TABLE(TicketID INT, SendTo VARCHAR(255))
DECLARE #ThisTicketID INT
, #MailMessage NVARCHAR(2000)
, #MailSubject NVARCHAR(255)
, #SendTo VARCHAR(255)
INSERT INTO #MailList
([TicketID], [SendTo])
SELECT t.[ID], u.[UserEmail]
FROM dbo.YourTicketTable t
JOIN dbo.YourUserTable u
ON t.UserCreated = u.ID
WHERE [StatusID] = 4
WHILE EXISTS(SELECT 1 FROM #MailList)
BEGIN
SELECT TOP(1) #ThisTicketID = [TicketID]
, #MailSubject = 'Ticket ' + CAST([TicketID] AS VARCHAR(10)) + ' is in status 4.'
, #MailMessage = 'Please review, or whatever, ticket ' + CAST([TicketID] AS VARCHAR(10)) + '.'
, #SendTo = COALESCE([SendTo], 'yourEmailAddress#InCase.Missing')
FROM #MailList
ORDER BY [TicketID];
DECLARE #mailitem_id INT ;
EXEC [msdb].dbo.[sp_send_dbmail]
#profile_name = 'SomeDBMailProfileName' -- sysname
, #recipients = #SendTo -- varchar(max)
, #subject = #MailSubject -- nvarchar(255)
, #body = #MailMessage -- nvarchar(max)
, #mailitem_id = #mailitem_id OUTPUT -- int
, #from_address = 'you#you.com' -- varchar(max)
, #reply_to = 'you#you.com' -- varchar(max)
DELETE #MailList
WHERE [TicketID] = #ThisTicketID
END
END
Basically you will use something like this for your job.
exec sp_send_dbmail
#profile_name = 'your_mail_profile'
,#recipients = 'you#email.com'
,#subject = 'Attended'
,#query = 'select * from yourTable where [status] = 4'
--,#attach_query_result_as_file = 1
--,#query_attachment_filename = 'somefile.csv'
See other options in the docs... and adjust accordingly.

Unable to delete records from SQL Server tables using stored procedure

I'm developing a desktop application for inventory management.
I have 3 tables in SQL Server:
TRANSACTIONS
MATERIAL_TRANSACTION
TRANSACTION_DETAILS
I've created a stored procedure to insert as well as update all the above mentioned tables.
TRANSACTIONS is my master table. So, I use update query to update its columns.
But records of the other two tables, which are the detail tables, need to be deleted before inserting new rows in the database.
I'm unable to delete the rows in this stored procedure. Please help!
I've used the following SQL Server stored procedure
ALTER PROCEDURE [dbo].[SAVE_TRANSACTION]
#ID NVARCHAR(50),
#REF_NO NVARCHAR(50),
#VCH_DATE DATE,
#VCH_TYPE INT,
#CR_AC INT,
#DR_AC INT,
#DOCKET_NO NVARCHAR(50),
#TRANSPORT NVARCHAR(50),
#DELIVERY_NOTE NTEXT,
#S_NAR NVARCHAR(100),
#L_NAR NTEXT,
#IS_REVERSE_CHARGE INT,
#INVOICE_REF INT,
#BUYER NVARCHAR(50),
#BUYER_CONTACT NVARCHAR(50),
#BUYER_ADDRESS NTEXT,
#BUYER_GSTIN NVARCHAR(50),
#BUYER_STATE NVARCHAR(50),
#BUYER_REG_TYPE INT,
#MATERIAL_TRANSACTION dbo.TVP_MATERIAL_TRANSACTION READONLY,
#TRANSACTION_DETAILS dbo.TVP_TRANSACTION_DETAILS READONLY,
#RETURN INT OUTPUT
AS
DECLARE #TRAN_ID INT
BEGIN
SET NOCOUNT ON;
DELETE FROM MATERIAL_TRANSACTION
WHERE ID > 0
AND TRANSACTION_ID = #ID;
DELETE FROM TRANSACTION_DETAILS
WHERE ID > 0
AND TRANSACTION_ID = #ID;
IF (#ID = 0)
BEGIN
INSERT INTO dbo.TRANSACTIONS(REF_NO, VCH_DATE, VCH_TYPE, CR_AC, DR_AC,
DOCKET_NO, TRANSPORT, DELIVERY_NOTE,
S_NAR, L_NAR, IS_REVERSE_CHARGE,
INVOICE_REF, BUYER, BUYER_CONTACT, BUYER_ADDRESS,
BUYER_GSTIN, BUYER_STATE, BUYER_REG_TYPE)
VALUES (#REF_NO, #VCH_DATE, #VCH_TYPE, #CR_AC, #DR_AC,
#DOCKET_NO, #TRANSPORT, #DELIVERY_NOTE,
#S_NAR, #L_NAR, #IS_REVERSE_CHARGE,
#INVOICE_REF, #BUYER, #BUYER_CONTACT, #BUYER_ADDRESS,
#BUYER_GSTIN, #BUYER_STATE, #BUYER_REG_TYPE);
SET #TRAN_ID = ##IDENTITY
END
ELSE
BEGIN
UPDATE dbo.TRANSACTIONS
SET REF_NO = #REF_NO,
VCH_DATE = #VCH_DATE, VCH_TYPE = #VCH_TYPE,
CR_AC = #CR_AC, DR_AC = #DR_AC,
DOCKET_NO = #DOCKET_NO,
TRANSPORT = #TRANSPORT, DELIVERY_NOTE = #DELIVERY_NOTE,
S_NAR = #S_NAR, L_NAR = #L_NAR,
IS_REVERSE_CHARGE = #IS_REVERSE_CHARGE,
INVOICE_REF = #INVOICE_REF,
BUYER = #BUYER, BUYER_CONTACT = #BUYER_CONTACT,
BUYER_ADDRESS = #BUYER_ADDRESS,
BUYER_GSTIN = #BUYER_GSTIN, BUYER_STATE = #BUYER_GSTIN,
BUYER_REG_TYPE = #BUYER_REG_TYPE
WHERE
ID = #ID;
SET #TRAN_ID = #ID;
END
--UPDATE MATERIAL_TRANSACTION SET IS_DELETED=1 WHERE TRANSACTION_ID=#ID;
-- UPDATE TRANSACTION_DETAILS SET IS_DELETED=1 WHERE TRANSACTION_ID=#ID;
INSERT INTO TRANSACTION_DETAILS (TRANSACTION_ID, AC_ID, TRAN_TYPE,
CR_AMT, DR_AMT, AMT_PERCENT, IS_PARENT)
SELECT
#TRAN_ID, [AC_ID], [TRAN_TYPE],
[CR_AMT], [DR_AMT], [AMT_PERCENT], [IS_PARENT]
FROM
#TRANSACTION_DETAILS TVP
INSERT INTO MATERIAL_TRANSACTION (TRANSACTION_ID, PRODUCT_ID, QTY,
UNIT_ID, DESCRIPTION, HSN_CODE,
PRICE, DISCOUNT_AMT, DISCOUNT_PERCENT,
CGST_PERCENT, SGST_PERCENT, IGST_PERCENT,
CGST_AMT, SGST_AMT, IGST_AMT)
SELECT
#TRAN_ID, [PRODUCT_ID], [QTY],
[UNIT_ID], [DESCRIPTION], [HSN_CODE],
[PRICE], [DISCOUNT_AMT], [DISCOUNT_PERCENT],
[CGST_PERCENT], [SGST_PERCENT], [IGST_PERCENT],
[CGST_AMT], [SGST_AMT], [IGST_AMT]
FROM
#MATERIAL_TRANSACTION TVP
SELECT #RETURN = #TRAN_ID
END

Set parameters in a stored procedure that returns a resultset

I'm trying to consolidate some code but before I open this particular can of worms I wanted to find out from you guys. If I have several stored procedures...
sproc1 - "master proc" which sets #test
sproc2 - proc that executes if #test exists and returns both a resultset and (if possible) resets #serial
sproc3 - proc that executes if #test does not exist and returns both a resultset and (if possible) resets #serial
sproc1
#leftStack INT,
#leftTray INT,
#midStack INT,
#midTray INT,
#rightStack INT,
#rightTray INT
AS
DECLARE #soLineNumber varchar(50)
DECLARE #serial VARCHAR(50)
DECLARE #rack INT
DECLARE #tray INT
DECLARE #position INT
SELECT #test = oL.[SERIAL_NUMBER]
FROM [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_ORDER_OPTICS] AS oL
WHERE NOT EXISTS
(
SELECT [SERIAL_NUMBER]
FROM [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_OPTIC_RESULTS] AS rL
WHERE oL.[SERIAL_NUMBER] = rL.[SERIAL_NUMBER]
)
AND NOT EXISTS
(
SELECT [SERIAL_NUMBER]
FROM [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_OPTIC_INSERTED] AS oI
WHERE oL.[SERIAL_NUMBER] = oI.[SERIAL_NUMBER]
)
-- AND oL.[SO_LINE_NUMBER] = #soLineNumber --pick regardless of SO line number, to reduce gaps between lines
AND ((oL.[RACK] = #leftStack AND oL.[TRAY] = #leftTray)
OR (oL.[RACK] = #midStack AND oL.[TRAY] = #midTray)
OR (oL.[RACK] = #rightStack AND oL.[TRAY] = #rightTray))
ORDER BY [SO_LINE_NUMBER] ASC
IF NULLIF(#test, '') IS NOT NULL
BEGIN
EXEC sproc2
END
IF NULLIF(#test, '') IS NULL
BEGIN
EXEC sproc3
END
UPDATE [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_ORDER_OPTICS] SET [PICKED] = 'True' WHERE [SERIAL_NUMBER] = #serial
END
My questions:
1) how can I reset #serial from sproc2 and sproc3?
2) in an ADO recordset query, will the results from the executed stored procedures pull in, if so, how?
For this to work sproc2 and sproc3 should been defined like this:
CREATE PROC sproc2 #test VARCHAR(50), #serial VARCHAR(50) OUTPUT
What this does is, it sends the value of #test as a value param. The OUTPUT keyword on #serial enables you to keep track of any changes done on #serial.

Stored procedure only updates when running it from Management studio

So yea. I have this really weird problem. I have the following stored procedure
ALTER PROCEDURE [CP24SHOP].[sp_part_set_status_bulk]
#user nvarchar(max),
#doerTicket VARCHAR ( 200 ) = null,
#status int,
#items CP24SHOP.udt_parts READONLY
AS
BEGIN
SET NOCOUNT ON;
-- Check security
exec websocket.sp_validate_user
#user,
#doerTicket out
-- foreach row in #items, update the status
MERGE INTO [file].ItemPart WITH ( XLOCK, ROWLOCK ) AS target
USING ( SELECT
item.GID
FROM #items AS item
) AS source
ON ( target.GID = source.GID )
WHEN MATCHED THEN
UPDATE SET
target.[Status] = #status,
target.DateTimeModified = GETDATE();
select 'bob'
RETURN 0
END
and when I run it from Management Studio with this code
declare #user nvarchar(max) = 'websocket'
DECLARE #list CP24SHOP.udt_parts
INSERT INTO #list
(
GID
)
VALUES
(
-7228376
)
select [Status] from [file].ItemPart
where GID = -7228376
exec CP24SHOP.sp_part_set_status_bulk
#user = #user,
#items = #list,
#status = '155'
select [Status], DateTimeModified from [file].ItemPart
where GID = -7228376
it updates the status without problem
but when calling it through our websocket it runs the code and returns "bob" as it should, but when I check the database the status of the item hasn't updated. I'm clueless as to what might be wrong
err - I think you're missing a commit.
Looks to me like you are updating & then rolling back!

Insert/Update Stored Procedure has conversion error

I am trying to make one stored procedure only in SQL Server that lets the user to choose if he/she wants to add or update a record. Below is my code for my stored pro:
CREATE PROCEDURE Sproc_INSERTUPDATE_tblProducts
#ProductID bigint,
#ProductName varchar(50),
#Description varchar(50),
#Price money,
#DateCreated datetime,
#DateUpdated datetime,
#Choice bit output
AS
BEGIN
Select #Choice
If #Choice = 0
Begin
Insert into tblProducts (
ProductID,
ProductName,
Description,
Price,
DateCreated,
DateUpdated)
values (#ProductID,
#ProductName,
#Description,
#Price,
#DateCreated,
#DateUpdated)
Select * from tblProducts
End
Else If #Choice = 1
Begin
Update tblProducts Set ProductID = #ProductID,
ProductName = #ProductName,
Description = #Description,
Price = #Price,
DateCreated = #DateCreated,
DateUpdated = #DateUpdated
Select * from tblProducts
End
Else
Begin
Print 'Invalid choice. Please choose 0 or 1 only.'
End
END
GO
And here is my code for executing the stored pro I made:
USE StoreDB
Execute Sproc_INSERTUPDATE_tblProducts 4, 'Lotus', 'Flower', 85, GetDate, GetDate, 0
I don't encounter any errors with my stored pro but when I try to execute using a new query, I get this error message:
GetDate(): Error converting data type nvarchar to datetime.
You cannot pass a function such as getdate() into a stored proc. Declare a datetime variable and use that instead.
Declare #now datetime = getdate();
Execute Sproc_INSERTUPDATE_tblProducts 4, 'Lotus', 'Flower', 85, #now, #now, 0
Try this?
Execute Sproc_INSERTUPDATE_tblProducts 4, 'Lotus', 'Flower', 85, GetDate(), GetDate(), 0