The stored Procedure below used to insert/ update the sql database
ALTER PROCEDURE [dbo].[uspInsertorUpdate]
#dp char(32),
#dv char(32),
#e_num char(12),
#mail varchar(50),
#emerg char(32),
#opt1 char(16),
#stat char(20),
#e_id char(35),
#e_tit varchar(64),
#e_date datetime
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS (SELECT 1 FROM [dbo].[sampleemployee] WHERE e_id= #e_id)
BEGIN
UPDATE [dbo].[sampleemployee]
SET dp = #dp,
dv = #dv,
e_num = #e_num,
mail = #mail,
emerg = #emerg,
opt1 = #opt1,
stat = #stat,
e_tit = #e_tit,
e_date = #e_date
WHERE e_id = #e_id
END
ELSE
BEGIN
INSERT INTO [dbo].[sampleemployee]( dp, dv, e_num, mail, emerg, opt1, stat, e_id, e_tit, e_date)
VALUES ( #dp, #dv, #e_num, #mail, #emerg, #opt1, #stat, #e_id, #e_tit, #e_date );
END
END;
But it just inserts one row.But, I have set of records from Oracle database which I have to insert/update depending on the e_id in to SQA database.Not sure what needs to be changed.
The conditional statement looks good, but it seems that #e_id is not matching e_id. In cases like this, I write simpler statements for debugging purposes:
IF EXISTS (SELECT 1 FROM [dbo].[sampleemployee] where e_id = 'some known value')
BEGIN
PRINT 'YES'
END
ELSE
BEGIN
PRINT 'NO'
END
Maybe this will help point out something you're overlooking. Is #e_id an exact match for e_id, or do you have some cleanup to do?
Related
So I created a Stored Procedure in SQL that does 4 things
Create Order into Customer Order table
Create Order lines on Customer Order Line table
Update Auto number column by taking current value and adding 1
Update Purchase Order with Customer Order ID
Sends email to notify that an order has been created.
It works awesome if I execute each part separately or execute the whole Stored Procedure manually by sending command EXEC dbo.POIMPORT_UK #PO_NUM = 123456
But when I create a PO and it triggers the inserts, query 1,3,4,5 work but 2 doesn't for some reason. I can only get it to go if I fire off that procedure manually. Any thoughts?
USE [RIPTST]
GO
/****** Object: StoredProcedure [dbo].[POIMPORT_UK] Script Date: 8/20/2018 11:21:23 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[POIMPORT_UK]
#PO_NUM NVARCHAR(15)
AS
SET NOCOUNT ON
--For synchronization machine id placement
--Query 1
INSERT INTO CUSTOMER_ORDER(ID, CUSTOMER_ID, SITE_ID, SELL_RATE, BUY_RATE,
TERMS_NET_TYPE, TERMS_DISC_TYPE, FREIGHT_TERMS, BACK_ORDER, STATUS,
POSTING_CANDIDATE, MARKED_FOR_PURGE, CURRENCY_ID, CUSTOMER_PO_REF,
WAREHOUSE_ID, DESIRED_SHIP_DATE) SELECT (SELECT Next_number FROM
NEXT_NUMBER_GEN where rowid =
'72'),'ABECO','101RIPUS','1.0','1.0','A','A','P','N','F','N','N','(USD)
$',ID,'CROM',Getdate() FROM PURCHASE_ORDER WHERE ID = #PO_NUM
--Query 2
INSERT INTO CUST_ORDER_LINE
(CUST_ORDER_ID,LINE_NO,PART_ID,LINE_STATUS,ORDER_QTY,USER_ORDER_QTY,
SELLING_UM,UNIT_PRICE,SITE_ID,MISC_REFERENCE,PRODUCT_CODE,COMMODITY_CODE,
DRAWING_ID,DRAWING_REV_NO,MAT_GL_ACCT_ID,LAB_GL_ACCT_ID,BUR_GL_ACCT_ID,
SER_GL_ACCT_ID,GL_REVENUE_ACCT_ID,TOTAL_AMT_ORDERED,ENTERED_BY,WAREHOUSE_ID)
SELECT(select id from customer_order where CUSTOMER_PO_REF = #PO_NUM),
LINE_NO,PURC_ORDER_LINE.PART_ID,'A',ORDER_QTY,USER_ORDER_QTY,
PURCHASE_UM,PURC_ORDER_LINE.UNIT_PRICE,'101RIPUS',PART.DESCRIPTION,
PART.PRODUCT_CODE,PART.COMMODITY_CODE,PART.DRAWING_ID,PART.DRAWING_REV_NO,
PART_SITE.MAT_GL_ACCT_ID,PART_SITE.LAB_GL_ACCT_ID,PART_SITE.BUR_GL_ACCT_ID,
PART_SITE.SER_GL_ACCT_ID,
(SELECT REV_GL_ACCT_ID FROM PRODUCT WHERE CODE = PART.PRODUCT_CODE),
USER_ORDER_QTY*PURC_ORDER_LINE.UNIT_PRICE,'SYSADM',
PART_SITE.PRIMARY_WHS_ID From PURC_ORDER_LINE
Inner Join PART On PART.ID = PURC_ORDER_LINE.PART_ID
Inner Join PART_SITE On PART_SITE.PART_ID = PART.ID
WHERE PURC_ORDER_ID = #PO_NUM AND PART_SITE.sITE_ID = '101RIPUS'
--Query 3
Update NEXT_NUMBER_GEN Set Next_number = Next_number + 1 where rowid = '72'
--Query 4
Update PURCHASE_ORDER Set SALES_ORDER_ID = (select id from customer_order where CUSTOMER_PO_REF = #PO_NUM) where id = #PO_NUM
--Query 5
Declare #PO NVARCHAR(15) = #PO_NUM
Declare #CO NVARCHAR(15) = (select id from customer_order where CUSTOMER_PO_REF = #PO)
Declare #MYBODY VARCHAR(MAX) = 'Hello Test CSR,
A new internal order has been created for Ripley UK.
Test US Customer Order Number: ' + #CO +
'
Test UK Purchase Order Number: ' + #PO
EXEC msdb.dbo.sp_send_dbmail #profile_name='office365',
#recipients='test#test.com',
#subject='Test UK - Internal Order',
#body= #MYBODY
SET NOCOUNT OFF
Insert Trigger
USE [RIPTST]
GO
/****** Object: Trigger [dbo].[INSERT_PURCHASE_ORDER] Script Date: 8/20/2018 1:42:15 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER trigger [dbo].[INSERT_PURCHASE_ORDER] ON [dbo].[PURCHASE_ORDER] FOR INSERT AS
DECLARE
#nRcd INT,
#ID NVARCHAR(15),
#VENDOR_ID NVARCHAR(15),
#SITE_ID NVARCHAR(15),
#STATUS NCHAR,
#TOTAL_AMT_ORDERED DEC(15,2),
#TOTAL_AMT_RECVD DEC(15,2),
#SELL_RATE DEC(17,8),
#nCurrDigits INT,
#sEntityID NVARCHAR(15),
#ORDER_DATE DATETIME
SELECT #nRcd = 0
SET NOCOUNT ON
DECLARE PURCHASE_ORDER_INS CURSOR LOCAL FOR SELECT ID, VENDOR_ID, STATUS, TOTAL_AMT_ORDERED, TOTAL_AMT_RECVD, SELL_RATE, ORDER_DATE, SITE_ID FROM INSERTED
OPEN PURCHASE_ORDER_INS
FETCH PURCHASE_ORDER_INS INTO #ID, #VENDOR_ID, #STATUS, #TOTAL_AMT_ORDERED, #TOTAL_AMT_RECVD, #SELL_RATE, #ORDER_DATE, #SITE_ID
WHILE (#nRcd = 0 and ##FETCH_STATUS <> -1)
BEGIN
EXEC EXE_DETECT_EVENT 'P', #ID, NULL, NULL, 'I'
If #TOTAL_AMT_ORDERED + #TOTAL_AMT_RECVD != 0
SELECT #nRcd = 30881
If #nRcd = 0 And (#STATUS = 'R' Or #STATUS = 'F') And #TOTAL_AMT_ORDERED > #TOTAL_AMT_RECVD
BEGIN
select #nCurrDigits = c.i_curr_digits, #sEntityID = s.entity_id from CURRENCY c, ACCOUNTING_ENTITY ae, SITE s where s.id = #SITE_ID and ae.id = s.entity_id and ae.functional_currency_id = c.id
IF NOT EXISTS ( SELECT VENDOR_ID FROM VENDOR_ENTITY WHERE vendor_id = #VENDOR_ID and entity_id = #sEntityID )
INSERT INTO VENDOR_ENTITY ( VENDOR_ID, ENTITY_ID ) VALUES ( #VENDOR_ID, #sEntityID )
update VENDOR_ENTITY set
total_open_orders = total_open_orders + ROUND((#TOTAL_AMT_ORDERED - #TOTAL_AMT_RECVD) * #SELL_RATE, #nCurrDigits),
open_order_count = open_order_count + 1
where vendor_id = #VENDOR_ID and entity_id = #sEntityID
END
UPDATE VENDOR set last_order_date = #ORDER_DATE where id = #VENDOR_ID
FETCH PURCHASE_ORDER_INS INTO #ID, #VENDOR_ID, #STATUS, #TOTAL_AMT_ORDERED, #TOTAL_AMT_RECVD, #SELL_RATE, #ORDER_DATE, #SITE_ID
END
BEGIN
IF #VENDOR_ID = 'RIP01' AND #SITE_ID = '111RIPUK'
EXEC dbo.POIMPORT_UK #PO_NUM = #ID
END
DEALLOCATE PURCHASE_ORDER_INS
IF (#nRcd <> 0) RAISERROR('VMFG-%d error in trigger INSERT_PURCHASE_ORDER', 16, -1, #nRcd)
IF (#nRcd <> 0 Or ##ERROR <> 0) ROLLBACK TRANSACTION
The whole "inserting multiple records with XML" has pretty much been superseded by table parameters in SQL Server 2008.
CREATE PROCEDURE [Booking].[PlannerQuotation]
(#PlannerQuoatetionXML XML,
#ResponseXML XML OUTPUT)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #PlannerID INT
,#CustomerName NVARCHAR(100)
,#MobileNumber NVARCHAR(20)
,#ToAddress NVARCHAR(256)
,#Subject NVARCHAR(100)
,#Message NVARCHAR(100)
,#QuotationEmailBody NVARCHAR(100)
,#QuotationStatus NVARCHAR(100)
,#UserID INT --Comment : 1
,#EntityID INT --Comment : 1
,#ID INT
BEGIN TRY
BEGIN TRANSACTION
--select details
SELECT
#CustomerName = Plannerxml.nref.value('./CustomerName[1]', 'NVARCHAR(100)')
,#PlannerID = Plannerxml.nref.value('./PlannerID[1]', 'INT') --Comment : 1
,#UserID = Plannerxml.nref.value('./UserID[1]', 'INT') --Comment : 1
,#MobileNumber = Plannerxml.nref.value('./MobileNumber[1]', 'NVARCHAR(20)')
,#ToAddress = Plannerxml.nref.value('./ToAddress[1]', 'NVARCHAR(256)')
,#Subject = Plannerxml.nref.value('(./Subject[1])', 'VARCHAR(100)')
,#Message = Plannerxml.nref.value('./Message[1]', 'NVARCHAR(100)')
,#QuotationEmailBody = Plannerxml.nref.value('(./QuotationEmailBody[1])', 'VARCHAR(100)')
,#QuotationStatus = Plannerxml.nref.value('./QuotationStatus[1]', 'NVARCHAR(100)')
--,#IsSystemPlan = Plannerxml.nref.value('./IsSystemPlan[1]', 'TINYINT')
--,#ExpireDate = CAST(REPLACE(REPLACE(Plannerxml.nref.value('(./ExpireDate[1])', 'varchar(22)'), 'T', ' '), 'TZ', ' ') AS DATETIME)
--,#StartDate = CAST(REPLACE(REPLACE(Plannerxml.nref.value('(./StartDate[1])', 'varchar(22)'), 'T', ' '), 'TZ', ' ') AS DATETIME)
-- Mode of Operation will contain 3 Options - Copy,Move,Rename
FROM
#PlannerQuoatetionXML.nodes('//PlannerQuoatetionRQ') AS Plannerxml(nref)
--select Planner id
--SELECT #plannerID = tblPlanner.colPlannerID.value('#PlannerID', 'int')
--FROM #PlannerQuoatetionXML.nodes('PlannerQuoatetionRQ/Planners/Planner') tblPlanner(colPlannerID)
SELECT
#EntityID = P.EntityID
FROM
Booking.Planner
WHERE
PlannerID = #PlannerID
AND IsActive = 1
AND ISNULL(IsDeleted, 0) = 0
-- If Operation is Copy and new planner
-- create new planner
IF (UPPER(#ModeofOperation) = 'COPY'AND Isnull(#CopytoPlannerID, 0) = 0)
BEGIN
-- Insert New planner name into Planner table
IF NOT EXISTS (SELECT 1
FROM Booking.Planner
WHERE PlannerName = #PlannerName
AND EntityID = #EntityID
AND IsActive = 1
AND ISNULL(IsDeleted, 0) = 0)
BEGIN
--insert into planner
INSERT INTO Booking.PlannerQuotation (PlannerID, CustomerName,
MobileNumber, ToAddress,
Subject, Message,
QuotationEmailBody,
QuotationStatus,
IsActive,
CreatedBy, CreatedDate)
VALUES (#PlannerID, #CustomerName,
#MobileNumber, #ToAddress, #Subject, #Message,
#QuotationEmailBody, #QuotationStatus, 1,
#UserID, [Entity].[GetEntityDateTime](#EntityID))
SELECT #ID = SCOPE_IDENTITY()
END
ELSE
BEGIN
EXEC Logging.HandleError 60208, 'en-US'
END
END
ELSE
BEGIN
SET #ID = #PlannerID
END
SET #ResponseXML = '<Response><PlannerQuotationID>'+ CAST(#ID AS VARCHAR(MAX))+'</PlannerQuotationID></Response>'
--end update planner and details record
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF (##TRANCOUNT > 0)
BEGIN
ROLLBACK TRANSACTION
END
IF (ERROR_NUMBER() < 60000)
BEGIN
EXEC Logging.InsertFailedTransactionLog 'PlannerQuotationInsert'
,#PlannerQuotationXML
END
EXEC Logging.InsertLogError
END CATCH
END
I use SQL Server 2008 in my web application back end. Apparently I iterate through all the records from the C# code whenever there is a multiple insertion scenario. I have never tried the multiple insert using XML. And I think after reading many blogs about XML manipulation using SQL Server 2008 the process is pretty tedious ..
So my question is: is inserting via XML more efficient than the traditional inserts?
I'm running SQL Server 2008 R2 and I have a trigger that inserts into a table where asql agent job then kicks off every 10 sec's to run a sp to send an email notification. The problem that I'm running into is it appears that when a large number of inserts happen simultaneously the notifications can hang up and not get sent out for several minutes (sometimes as long as an hour) after the insert happens.The tb_BatchEmail only receives a few inserts (2-3) at a time, it's the Orders tables that can have several dozen inserts happen at once. So my question is - Is this the best way to setup this type of trigger or is there a better way that is more efficient and won't lag behind when loads of table inserts happen at once?
Here is the trigger:
ALTER TRIGGER [dbo].[VoceraOeOrders] ON [dbo].[Orders]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.tb_BatchEmail (
BatchEmailID
,[To]
,Body
,[Subject]
,[Profile]
,OrderID
,OrderDateTime
,SentDateTime
)
SELECT '0'
,'some_email'
,CASE
WHEN RoomTreatmentID IS NULL
THEN 'No Room#'
ELSE RoomTreatmentID
END + '-' + OrderedProcedureName
,CASE
WHEN Category = 'US'
THEN 'Stat Ultra Sound'
WHEN Category = 'NUC'
THEN 'Stat Nuclear'
WHEN Category = 'ECHO'
THEN 'Stat Echo'
WHEN Category = 'CT'
THEN 'Stat C T'
WHEN Category = 'MRI'
THEN 'Stat M R I'
WHEN Category = 'XRAY'
THEN 'Stat Xray'
ELSE 'Stat Order Alerts'
END
,'Alert'
,OrderID
,OrderDateTime
,NULL
FROM inserted i
INNER JOIN dbo.Patients pat
ON pat.VisitID = i.VisitID
AND pat.SourceID = i.SourceID
WHERE Priority = 'STAT'
AND Category IN ('CT', 'MRI', 'XRAY', 'US', 'NUC', 'ECHO')
AND CurrentLocationID = 'ED'
END
And here is the sp that is set to kick off every 10 seconds via server agent job:
ALTER PROCEDURE [dbo].[sp_SendVoceraMail]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #Id INT
DECLARE #To VARCHAR(250)
DECLARE #Body VARCHAR(250)
DECLARE #Subject VARCHAR(50)
DECLARE #ProfileName VARCHAR(20)
WHILE (
SELECT count(*)
FROM tb_BatchEmail
WHERE BatchEmailID = 0
) > 0
BEGIN
SELECT TOP 1 #Id = Id
,#To = [To]
,#Body = Body
,#Subject = [Subject]
,#ProfileName = [Profile]
FROM tb_BatchEmail
WHERE BatchEmailID = 0
EXEC msdb.dbo.sp_send_dbmail #recipients = #To
,#body = #Body
,#subject = #Subject
,#profile_name = #ProfileName
UPDATE tb_BatchEmail
SET BatchEmailID = 1
,SentDateTime = GETDATE()
WHERE Id = #Id
END
END
I am new to stored procedure and managed to google, to create a stored procedure for inserting or updating the database. The set of records are selected from the Oracle Database and depending on the em_id it hase to be iserted or updated in to the Sql Database table using BizTalk
Trying to create a stored procedure to insert or update records depending on a field.
CREATE PROCEDURE [dbo].[usp_InsertorUpdateDB]
#dp_id char(32),
#dv_id char(32),
#em_number char(12),
#email varchar(50),
#emergency_relation char(32),
#option1 char(16),
#status char(20),
#em_id char(35),
#em_title varchar(64),
#date_hired datetime
AS
MERGE [dbo].[em] AS [Target]
USING (SELECT #dp_id, #dv_id , #em_number, #email, #emergency_relation, #option1, #status, #em_id, #em_title, #date_hired)
AS [Source] ([dp_id], [dv_id], [em_number], [email], [emergency_relation], [option1], [status], [em_id], [em_title], [date_hired])
ON [Target].[em_id] = [Source].[em_id]
WHEN MATCHED THEN
UPDATE SET [dp_id] = [Source].[dp_id],
[dv_id] = [Source].[dv_id],
[em_number] = [Source].[em_number],
[email] = [Source].[email],
[emergency_relation] = [Source].[emergency_relation],
[option1] = [Source].[option1],
[status] = [Source].[status],
[em_id] = [Source].[em_id],
[em_title] = [Source].[em_title],
[date_hired] = [Source].[date_hired]
WHEN NOT MATCHED THEN
INSERT ([dp_id], [dv_id], [em_number], [email], [emergency_relation], [option1], [status], [em_id], [em_title],[date_hired])
VALUES ([Source].[dp_id], [Source].[dv_id], [Source].[em_number], [Source].[email], [Source].[emergency_relation], [Source].[option1], [Source].[status], [Source].[em_id], [Source].[em_title], [Source].[date_hired]);
GO
I asked a question two days before because it was showing
Incorrect syntax near the keyword 'WHEN'.
There was a comment showing the code is prone deadlock. Since I am new to Stored Procedures I dont know how to create a stored procedure for insert or update without deadlocks.I am really stuck.
Merge is the reason for deadlock, you can simply try that
CREATE PROCEDURE [dbo].[usp_InsertorUpdateDB]
#dp_id char(32),
#dv_id char(32),
#em_number char(12),
#email varchar(50),
#emergency_relation char(32),
#option1 char(16),
#status char(20),
#em_id char(35),
#em_title varchar(64),
#date_hired datetime
AS
IF ( (SELECT COUNT(em_id) FROM [dbo].[em] WHERE em_id = #em_id) > 0)
UPDATE [dbo].[em]
SET
[dp_id] = #dp_id,
[dv_id] = #dv_id,
[em_number] = #em_number,
[email] = #email,
[emergency_relation] = #emergency_relation,
[option1] = #option1,
[status] = #status,
[em_id] = #em_id,
[em_title] = #em_title,
[date_hired] = #date_hired
WHERE em_id = #em_id
ELSE
INSERT INTO [dbo].[em] (dp_id, dv_id, em_number, email, emergency_relation, option1, [status], em_id, em_title,date_hired)
VALUES (#dp_id, #dv_id, #em_number, #email, #emergency_relation, #option1, #status, #em_id, #em_title, #date_hired);
GO
Code:
ALTER PROCEDURE [dbo].[SP_LMS_dealerorusercreation_IUDS]
#dealrid bigint,
#rid bigint,
#stateid bigint,
#regonid bigint,
#Locid bigint,
#pid varchar(MAX),
#address varchar(max),
#dealrname varchar(25),
#landno bigint,
#mobno bigint,
#altcontno bigint,
#email varchar(35),
#desig varchar(25),
#reporting varchar(30),
#status int,
#action varchar(10),
#CompanyId Uniqueidentifier
AS
DECLARE #TranStatus VARCHAR(5)
BEGIN TRY
BEGIN TRANSACTION
IF(#action='Insert')
BEGIN
INSERT INTO LMS_dealerorusercreation(
rid,
stateid,
regonid,
Locid,
addres,
dealrname,
landno,
mobno,
altcontno,
email,
desig,
reporting,
status,
CompanyId
)
VALUES(
#rid,
#stateid,
#regonid,
#Locid,
#address,
#dealrname,
#landno,
#mobno,
#altcontno,
#email,
#desig,
#reporting,
#status,
#CompanyId
)
SELECT #dealrid = dealrid FROM LMS_dealerorusercreation WHERE mobno = #mobno AND email = #email
EXEC [dbo].[SP_LMS_SetDealerProductMapping]
#dealerId = #dealrid,
#prodid = #pid
SET #TranStatus='TRUE';
END
IF(#action='Update')
BEGIN
UPDATE LMS_dealerorusercreation set rid= #rid,
stateid=#stateid,
regonid=#regonid,
Locid=#Locid,
addres=#address,
dealrname=#dealrname,
landno=#landno,
mobno=#mobno,
altcontno=#altcontno,
email=#email,
desig=#desig,
reporting=#reporting,
status=#status
WHERE dealrid=#dealrid
SET #TranStatus='TRUE';
END
IF(#action='Delete')
BEGIN
DELETE FROM LMS_dealerorusercreation WHERE dealrid=#dealrid
SET #TranStatus='TRUE';
END
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
DECLARE #AI VARCHAR(MAX)
DECLARE #EM VARCHAR(MAX);
SET #AI = 'Not Provided'
SET #EM = ERROR_MESSAGE();
EXEC USP_SetException
#ExceptionDetail = #EM,
#AdditionalInfo = #AI
SET #TranStatus='FALSE';
END CATCH
SELECT #TranStatus;
The error am getting is
Cannot insert the value NULL into column 'dealrid', table 'DB_LMS.dbo.LMS_dealerorusercreation'; column does not allow nulls. INSERT fails.
You need to do one of two things, either...
ensure that you pass in a non-null value for the column, or;
ensure that your column accepts a null value if that is a desired property of the field.
Errors I see in the code.
While inserting into the table LMS_dealerorusercreation, you never selected dealrid column. Please select the same.
INSERT INTO LMS_dealerorusercreation(
rid,
stateid,
regonid,
Locid,
addres,
dealrname,
landno,
mobno,
altcontno,
email,
desig,
reporting,
status,
CompanyId,
dealrid
)
VALUES(
#rid,
#stateid,
#regonid,
#Locid,
#address,
#dealrname,
#landno,
#mobno,
#altcontno,
#email,
#desig,
#reporting,
#status,
#CompanyId,
#dealrid
)
it is juat as the error message states.
you are trying to do an insert to a table where dealrid has been created with not null. if you look at your insert statement, you are not selecting and passing a value to it.