data not Showing when execute the stored procedure in Sql - sql-server

I write this code in my stored procedure:
ALTER PROC sp_ShowComplaintStatus (#pid bigint,
#compid int)
AS
BEGIN
SET NOCOUNT ON;
SELECT PId,
C.Compld,
CC.ComplCategory,
CSC.ComplSubCategName,
S.Status
FROM TN_Complaint C
INNER JOIN TN_ComplStatus CS ON C.Compld = CS.CompId
INNER JOIN Z_Status S ON CS.StatusId = S.StatusId
INNER JOIN Z_ComplCategory CC ON C.CompCategId = CC.ComplCategoryId
INNER JOIN Z_ComplSubCategory CSC ON C.ComplSubCategoryId = CSC.ComplSubCategoryId
WHERE PId = #pid
AND C.Compld = #compid;
END;
sp_ShowComplaintStatus 10001, 1000;
But when I execute my stored procedure, it doesn't show any records. It only show column name.

Related

How to SELECT from a temp table name, passed to a stored procedure?

I have temp table name? as an output from a stored procedure and I passed the name of created temp table to another stored procedure as an input parameter.
I want to SELECT Guid from #CalculationGuidTempTableName VARCHAR then insert into #CalcsGuids.
Here is my stored procedure:
CREATE PROCEDURE [dbo].[ret_Reports_ProxyVoucherAccounting]
(#CalculationGuidTempTableName VARCHAR(32))
AS
DECLARE #CalcsGuids TABLE ([Guid] UNIQUEIDENTIFIER PRIMARY KEY)
--INSERT INTO #CalcsGuids (SELECT * FROM + #CalculationGuidTempTableName)
--DROP TABLE #CalculationGuidTempTableName
WITH temp AS
(
SELECT
reference.DetailPureTitle,
reference.DetailCaption,
reference.Nature,
reference.Summarize
FROM
#CalcsGuids calcs
INNER JOIN
ret_vwPayrollCalculationBackPayForReport details ON details.CalculationGuid = calcs.[Guid]
LEFT JOIN
ret_PaymentAllocation payment ON payment.Guid = Details.ItemGuid
INNER JOIN
ret_vwFactorReferences reference ON reference.ItemGuid = Details.ItemGuid
INNER JOIN
ret_PayrollCalculationCommands command ON command.[Guid] = details.CalculationCommandGuid
WHERE
command.Approved = 1 AND command.Deleted = 0
GROUP BY
reference.DetailPureTitle,
reference.DetailCaption,
reference.Nature,
reference.Summarize
)
SELECT
*
FROM
temp
WHERE
PayAmount <> 0 OR
DeductionAmount <> 0 OR
EmployerAmount <> 0
ORDER BY
Nature
Try this :
INSERT INTO #CalcsGuids EXEC ('SELECT * FROM ' + #CalculationGuidTempTableName);

How do I add errror handling into this stored procedure?

How can I print an error message from this procedure if the employee (server) hasn't served anyone? Are try - catch blocks the only way to handle this?
I was thinking that if/else condition test followed by Print message suits my requirement.
Stored procedure:
if OBJECT_ID('customers_served', 'u') is not null
drop procedure customers_served;
go
create procedure customers_served
#employee_id int
as
set nocount on;
select
c.customer_id, c.cust_lastname,
(sum(c.cust_total_guests)) as total_guests
from
customers c
join
seating s on c.customer_id = s.customer_id
join
table_assignment ta on s.table_id = ta.table_id
join
employees e on ta.employee_id = e.employee_id
where
#employee_id = e.employee_id
group by
c.customer_id, c.cust_lastname;
/* if total_guests = 0 print message the employee has served 0 guests */
Test procedure:
exec customers_served
#employee_id = 5;
I modified your script to this.
use dbServers;
if OBJECT_ID('customers_served', 'u') is not null
drop procedure customers_served;
go
create procedure customers_served
#employee_id int
as
set nocount on;
declare #totalGuests int;
set #totalGuests = (
select(sum(c.cust_total_guests))
from customers c
join seating s on c.customer_id = s.customer_id
join table_assignment ta on s.table_id = ta.table_id
join employees e on ta.employee_id = e.employee_id
where #employee_id = e.employee_id
)
if #totalGuests = 0 OR #totalGuests IS NULL
BEGIN
print 'This server did not serve any guests'
END
else
BEGIN
select #totalGuests AS 'total_quests'
END
/* test procedure*/
exec customers_served
#employee_id = 5;
Following snippet of code might help:
declare #r int
select #r = (sum(c.cust_total_guests)) as total_guests
from customers c
join seating s on c.customer_id = s.customer_id
join table_assignment ta on s.table_id = ta.table_id
join employees e on ta.employee_id = e.employee_id
where #employee_id = e.employee_id
group by c.customer_id, c.cust_lastname;
if #r = 0
begin
-- do what ever you wish
end
else
begin
select c.customer_id, c.cust_lastname, (sum(c.cust_total_guests)) as
total_guests
from customers c
join seating s on c.customer_id = s.customer_id
join table_assignment ta on s.table_id = ta.table_id
join employees e on ta.employee_id = e.employee_id
where #employee_id = e.employee_id
group by c.customer_id, c.cust_lastname;
end
end
Rather than double querying, you can simply test ##ROWCOUNT after your query to determine if any results were returned, and print your message if ##ROWCOUNT = 0.

Executing stored procedure not working but individual statements working in stored procedure

I have the following stored procedure which I am trying to execute.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_Create]
(
#OriginatingTransactionID VARCHAR(50),
#AssociatedOriginatingTransactionID VARCHAR(50),
#LineOfBusiness VARCHAR(50),
#RiskState VARCHAR(50),
#OccupationCode VARCHAR(50),
#SourceSystem VARCHAR(50),
#DocumentCategory VARCHAR(50),
#DocumentType VARCHAR(50),
#TransactionFlow VARCHAR(50),
#BundleName VARCHAR(50),
#DocumentID VARCHAR(50),
#DocumentName VARCHAR(50),
#PolicyOrClaimNumber VARCHAR(50),
#EffectiveOrCreationDate DATETIME,
#SignatureDetect BIT
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #FinalDate DATETIME, #RuleID VARCHAR(50),
#RuleName VARCHAR(50), #CurrentActionID INT,
#BundleTransactionID INT
IF (#SignatureDetect = 'true')
BEGIN
IF (#OriginatingTransactionID = #AssociatedOriginatingTransactionID)
BEGIN
IF NOT EXISTS (SELECT t.Doc_Checklist_TXN_ID FROM (SELECT bundlechecklist.Bundle_TXN_ID, documentchecklist.Doc_Checklist_TXN_ID, documentchecklist.Doc_Type_Name FROM ecm.bundle_checklist_txn bundlechecklist
LEFT OUTER JOIN [ECM].[Document_Checklist_TXN] documentchecklist ON documentchecklist.Bundle_TXN_ID = bundlechecklist.Bundle_TXN_ID
WHERE bundlechecklist.originating_tran_id = #OriginatingTransactionID AND bundle_name = #BundleName)t WHERE t.Doc_Checklist_TXN_ID is not null )
BEGIN
UPDATE ecm.bundle_checklist_txn
SET Bundle_Status_Code = 'COMP'
FROM ecm.bundle_checklist_txn bundlechecklist
INNER JOIN (SELECT DISTINCT Bundle_TXN_ID,Document_ID FROM ecm.Document_Checklist_TXN documentchecklist
WHERE Doc_Status_Code='COMP') COMP
ON COMP.Bundle_TXN_ID = bundlechecklist.Bundle_TXN_ID
AND COMP.Bundle_TXN_ID NOT IN (
SELECT Bundle_TXN_ID FROM ecm.Document_Checklist_TXN documentchecklist
WHERE documentchecklist.Bundle_TXN_ID=COMP.Bundle_TXN_ID AND documentchecklist.Doc_Status_Code<>'COMP')
AND COMP.Document_ID=#DocumentID
WHERE bundlechecklist.Bundle_TXN_ID= #OriginatingTransactionID
AND bundlechecklist.Assoc_Orig_Tran_ID=#AssociatedOriginatingTransactionID
UPDATE associatedtransaction
SET Assoc_Orig_Status_Code='COMP'
FROM [ECM].[Assoc_Orig_Tran_TXN] associatedtransaction
INNER JOIN (SELECT DISTINCT Assoc_Orig_Tran_ID from [ECM].[Bundle_Checklist_TXN] bundlechecklist
WHERE bundlechecklist.[Bundle_Status_Code]='COMP')COMP
ON COMP.Assoc_Orig_Tran_ID=associatedtransaction.Assoc_Orig_Tran_ID
WHERE COMP.Assoc_Orig_Tran_ID=#AssociatedOriginatingTransactionID
END
END
END
ELSE
BEGIN
IF (#OriginatingTransactionID = #AssociatedOriginatingTransactionID)
BEGIN
SELECT #FinalDate =DATEADD(DAY,Number_Of_Days_Till_Next_Action,#EffectiveOrCreationDate),#RuleID= rule1.Action_Rule_ID,#RuleName=rule1.Action_Rule_Name,#currentActionID=rule1.Current_Action_ID FROM ecm.Action_Rule rule1
INNER JOIN ecm.Action_Rule_Group rulegroup ON rulegroup.Action_Rule_Group_ID = rule1.Action_Rule_Group_ID
INNER JOIN ref.Line_of_Business lob ON lob.Line_of_Business_Code = rulegroup.Line_of_Business_Code
INNER JOIN ref.State state ON state.State_Alpha_Code=rulegroup.State_Alpha_Code
INNER JOIN ref.Source_System sourcesystem ON sourcesystem.Source_System_ID = rulegroup.Source_System_ID
INNER JOIN ecm.[Document Catgeory] documentcategory ON documentcategory.Doc_Categ_ID = rulegroup.Doc_Categ_ID
INNER JOIN ecm.[Document Type] documenttype ON documenttype.Doc_Type_ID=rule1.Doc_Type_ID
INNER JOIN ecm.Exec_Acct_Group occupationgroup ON occupationgroup.Exec_Acct_Grp_ID = rulegroup.Exec_Acct_Grp_ID
INNER JOIN [ECM].[Bundle] bundle ON bundle.Bundle_ID = rule1.Bundle_ID
WHERE
bundle.Bundle_Name = #BundleName
AND rulegroup.Line_of_Business_Code=#LineOfBusiness
AND rulegroup.State_Alpha_Code=#RiskState
AND documentcategory.Doc_Categ_Name=#DocumentCategory
AND rulegroup.Exec_Acct_Grp_ID=#OccupationCode
AND rule1.Transaction_Flow=#TransactionFlow
AND sourcesystem.Source_System_Name = #SourceSystem
AND rulegroup.Doc_Categ_ID=documentcategory.Doc_Categ_ID
AND documenttype.Doc_Type_Name =#DocumentType
IF NOT EXISTS (SELECT Assoc_Orig_Tran_ID FROM [ECM].[Assoc_Orig_Tran_TXN] WHERE Assoc_Orig_Tran_ID=#AssociatedOriginatingTransactionID)
BEGIN
INSERT INTO [ECM].[ASsoc_Orig_Tran_TXN]
(Orig_Tran_Action_Rule_id, Assoc_Orig_Tran_ID, Assoc_Orig_Status_Code, First_Rule_Date, Final_Actionable_Date, Folder_ID,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#RuleID,#AssociatedOriginatingTransactionID, 'PEND', #EffectiveOrCreationDate, #FinalDate,NULL,GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
END
IF NOT EXISTS (SELECT originating_tran_id FROM ecm.bundle_checklist_txn WHERE originating_tran_id = #OriginatingTransactionID AND bundle_name = #BundleName)
BEGIN
INSERT INTO [ECM].[Bundle_Checklist_TXN]
( Bundle_Action_Rule_ID,Bundle_Name,Bundle_Status_Code,ASsoc_Orig_Tran_ID,Originating_Tran_ID,Doc_Categ_Name, Next_Action_Dt,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#RuleID,#BundleName,'PEND',#AssociatedOriginatingTransactionID,#OriginatingTransactionID,#DocumentCategory,#FinalDate,GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
END
IF NOT EXISTS (SELECT t.Doc_Checklist_TXN_ID FROM (SELECT bundlechecklist.Bundle_TXN_ID, documentchecklist.Doc_Checklist_TXN_ID, documentchecklist.Doc_Type_Name FROM ecm.bundle_checklist_txn bundlechecklist
LEFT OUTER JOIN [ECM].[Document_Checklist_TXN] documentchecklist ON documentchecklist.Bundle_TXN_ID = bundlechecklist.Bundle_TXN_ID
WHERE bundlechecklist.originating_tran_id = #OriginatingTransactionID AND bundle_name = #BundleName)t WHERE t.Doc_Checklist_TXN_ID is not null )
BEGIN
SELECT #BundleTransactionID=bundlechecklist.bundle_txn_id FROM [ECM].[Bundle_Checklist_TXN] bundlechecklist
INSERT INTO [ECM].[Document_Checklist_TXN]
(bundle_txn_id, document_action_rule_id, action_rule_name, doc_type_name, cp_document_name, document_id, doc_status_code,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#BundleTransactionID, #RuleID, #RuleName, #DocumentType, #DocumentName, #DocumentID, 'PEND',GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
END
END
END
END
In my code, if I execute with values, its not working and and insert fails
with the following error :
Msg 515, Level 16, State 2, Procedure usp_CreateChecklist, Line 95
Cannot insert the value NULL into column 'Orig_Tran_Action_Rule_id',
table 'EIC_ECM_Checklist.ECM.Assoc_Orig_Tran_TXN'; column does not
allow nulls. INSERT fails. The statement has been terminated.
Msg 515, Level 16, State 2, Procedure usp_CreateChecklist, Line 104
Cannot insert the value NULL into column 'Bundle_Action_Rule_ID',
table 'EIC_ECM_Checklist.ECM.Bundle_Checklist_TXN'; column does not
allow nulls. INSERT fails. The statement has been terminated.
Msg 515, Level 16, State 2, Procedure usp_CreateChecklist, Line 117
Cannot insert the value NULL into column 'Document_Action_Rule_ID',
table 'EIC_ECM_Checklist.ECM.Document_Checklist_TXN'; column does not
allow nulls. INSERT fails. The statement has been terminated.
But if I execute individually each line and its working and all values getting stored in the table. All insert statement works. Tried debugging with individual statement. Like below :
SELECT
DATEADD(DAY, Number_Of_Days_Till_Next_Action, '2015-10-18T00:00:00'),
rule1.Action_Rule_ID, rule1.Action_Rule_Name,
rule1.Current_Action_ID
FROM
ecm.Action_Rule rule1
INNER JOIN
ecm.Action_Rule_Group rulegroup ON rulegroup.Action_Rule_Group_ID = rule1.Action_Rule_Group_ID
INNER JOIN
ref.Line_of_Business lob ON lob.Line_of_Business_Code = rulegroup.Line_of_Business_Code
INNER JOIN
ref.State state ON state.State_Alpha_Code=rulegroup.State_Alpha_Code
INNER JOIN
ref.Source_System sourcesystem ON sourcesystem.Source_System_ID = rulegroup.Source_System_ID
INNER JOIN
ecm.[Document Catgeory] documentcategory ON documentcategory.Doc_Categ_ID = rulegroup.Doc_Categ_ID
INNER JOIN ecm.[Document Type] documenttype ON documenttype.Doc_Type_ID=rule1.Doc_Type_ID
INNER JOIN ecm.Exec_Acct_Group occupationgroup ON occupationgroup.Exec_Acct_Grp_ID = rulegroup.Exec_Acct_Grp_ID
INNER JOIN [ECM].[Bundle] bundle ON bundle.Bundle_ID = rule1.Bundle_ID
WHERE
bundle.Bundle_Name = 'Auto'
AND rulegroup.Line_of_Business_Code='A'
AND rulegroup.State_Alpha_Code='FL'
AND documentcategory.Doc_Categ_Name=' review'
AND rulegroup.Exec_Acct_Grp_ID=2
AND rule1.Transaction_Flow='Outgoing doc'
AND sourcesystem.Source_System_Name = 'V4 Policy'
AND rulegroup.Doc_Categ_ID=documentcategory.Doc_Categ_ID
AND documenttype.Doc_Type_Name ='Application'
SELECT Assoc_Orig_Tran_ID FROM [ECM].[Assoc_Orig_Tran_TXN] WHERE Assoc_Orig_Tran_ID='BPA201607131452113541050525A1REN'
INSERT INTO [ECM].[ASsoc_Orig_Tran_TXN]
(Orig_Tran_Action_Rule_id, ASsoc_Orig_Tran_ID, ASsoc_Orig_Status_Code, First_Rule_Date, Final_Actionable_Date, Folder_ID,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
('157','BPA201607131452113541050525A1REN', 'PEND','2015-10-18T00:00:00' , '2015-11-07 00:00:00.000',NULL,GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
SELECT originating_tran_id FROM ecm.bundle_checklist_txn WHERE originating_tran_id = 'BPA201607131452113541050525A1REN' AND bundle_name = 'Auto'
INSERT INTO [ECM].[Bundle_Checklist_TXN]
( Bundle_Action_Rule_ID,Bundle_Name,Bundle_Status_Code,ASsoc_Orig_Tran_ID,Originating_Tran_ID,Doc_Categ_Name, Next_Action_Dt,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
('157','Auto','PEND','BPA201607131452113541050525A1REN','BPA201607131452113545050525A1AMD','Underwriting review','2015-11-07 00:00:00.000',GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
declare #BundleTransactionID int
SELECT #BundleTransactionID=bundlechecklist.bundle_txn_id FROM [ECM].[Bundle_Checklist_TXN] bundlechecklist
INSERT INTO [ECM].[Document_Checklist_TXN]
(bundle_txn_id, document_action_rule_id, action_rule_name, doc_type_name, cp_document_name, document_id, doc_status_code,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#BundleTransactionID, '157', 'FL Application', 'Application', 'CPLProp_Acknowledgment_FAQs', '321Z01W_007624ZRM00002G', 'PEND',GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
Any idea where it fails?
First Error says that you are trying to insert null value to Orig_Tran_Action_Rule_id but this field is NOT NULL so u cannot insert the data.
INSERT INTO [ECM].[ASsoc_Orig_Tran_TXN]
(Orig_Tran_Action_Rule_id, Assoc_Orig_Tran_ID, Assoc_Orig_Status_Code, First_Rule_Date, Final_Actionable_Date, Folder_ID,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#RuleID,#AssociatedOriginatingTransactionID, 'PEND', #EffectiveOrCreationDate, #FinalDate,NULL,GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
Please check #RuleID.
And for other two also the same issue.
And you are right, when you insert individual at that time you provide values('157') instead of Variables(#RuleID).
So it works fine.

SQL query stored procedure

Create a stored procedure that passes in the SalesOrderID as a parameter.
This stored procedure will return the SalesOrderID, Date of the transaction, shipping date, city and state. It is not running
Ans:
Create PROCEDURE proc_findProductInfo
#SalesOrderID int,
#SalesOrderOut int OUTPUT,
#OrderDate datetime OUTPUT,
#ShipDate datetime OUTPUT,
#CityState varchar(100) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET #SalesOrderOut = #SalesOrderID
SET #OrderDate = (SELECT OrderDate FROM SALES.SalesOrderHeader )
SET #ShipDate = (SELECT ShipDate FROM Sales.SalesOrderHeader)
SET #CityState = (SELECT a.City, st.Name
FROM Sales.SalesOrderHeader s
INNER JOIN Person.Address a ON s.ShipToAddressID = a.AddressID
INNER JOIN Person.StateProvince st ON s.TerritoryID = st.TerritoryID
WHERE SalesOrderID = #SalesOrderID)
END
DECLARE #OrderNum int, #Date datetime, #qty1 int, #Date1 datetime
EXEC proc_findProductInfo 63936,
#SalesOrderOut = #OrderNum OUTPUT,
#OrderDate = #Date OUTPUT,
#ShipDate = #date1,
#CityState = #qty1 output
SELECT #OrderNum, #date, #qty1, #Date1
Error Message:
Msg 116, Level 16, State 1, Procedure proc_findProductInfo, Line 25
Only one expression can be specified in the select list when the
subquery is not introduced with EXISTS
You're making this way harder than it needs to be:
Create PROCEDURE proc_findProductInfo
#SalesOrderID int
AS
BEGIN
SET NOCOUNT ON;
SELECT s.SalesOrderID, s.OrderDate, s.ShipDate, a.City,st.Name
FROM Sales.SalesOrderHeader s
INNER JOIN Person.Address a ON s.ShipToAddressID = a.AddressID
INNER JOIN Person.StateProvince st ON s.TerritoryID=st.TerritoryID
WHERE s.SalesOrderID = #SalesOrderID
END
I'm not even sure you need the StateProvince table here... the question probably allows you to trust the Address record.
It is complaining about the following
SET #CityState = (
SELECT a.City,st.Name
You are selecting both City and State Name and trying to assign it to a variable.
You either need to concatenate or coalesce them into them into a single output or alternatively use the below type of select to assign each one to a variable.
select
#var1 = field1,
#var2 = field2,
...
As below
SET #SalesOrderOut = #SalesOrderID
SELECT #OrderDate = s.OrderDate,
#ShipDate = s.ShipDate,
#CityState = CONCAT(a.City, ", ", st.Name)
FROM Sales.SalesOrderHeader s
inner JOIN Person.Address a
ON s.ShipToAddressID = a.AddressID
inner JOIN Person.StateProvince st
on s.TerritoryID=st.TerritoryID
WHERE SalesOrderID = #SalesOrderID

how to insert into table but only if the record doesnt exist

I've got a table that stores the following:
JobID
ValidationItemID
CreatedBy
I want to be able to insert into this table (a predefined template) but only add rows that dont exist. What I mean by dont exist is the combination of JobID and ValidationItemID make the row unique. My procedure passes in a JobID, but I cannot pass in a validation item ID as I pull this column as part of the template...
Something to this effect:
CREATE PROCEDURE insTemplate
#JobID varchar(50),
#Login varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO
ValidationItemSignOff
(
JobID,
ValidationItemID,
CreatedBy
)
SELECT
DISTINCT
#JobID,
vi.ValidationItemID,
#Login
FROM
RunOffAnswer roa
INNER JOIN
Method m ON m.MethodID = roa.MethodID
INNER JOIN
RunOffValidationItem vi ON vi.ValidationItemID = m.ValidationItemID
WHERE
vi.Inactive=0
AND NOT EXISTS(SELECT * FROM ValidationItemSignOff WHERE JobID=#JobID AND vi.ValidationItemID ???
END
GO
I dont know how to phrase the where condition so that it doesn't reinsert the same JobID and ValidationItemID. Lets say I have inside the table:
Job ValidationItem
Job A 1
Job A 2
Job A 5
And I have a template with the following:
ValidationItem
1
2
3
4
5
6
When I run my stored procedure it should only insert values 3,4,6 from the template table, for the job id... So I need help with my where condition.
I think my issue is I cannot use NOT EXISTS, maybe I need to join back to this ValidationItemSignOff table itself on JobID and ValidationItemID where ValidationItemID is NULL, maybe like this:
CREATE PROCEDURE insTemplate
#JobID varchar(50),
#Login varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO
ValidationItemSignOff
(
JobID,
ValidationItemID,
CreatedBy
)
SELECT
DISTINCT
#JobID,
vi.ValidationItemID,
#Login
FROM
RunOffAnswer roa
INNER JOIN
Method m ON m.MethodID = roa.MethodID
INNER JOIN
RunOffValidationItem vi ON vi.ValidationItemID = m.ValidationItemID
RIGHT OUTER JOIN
ValidationItemSignOff viso ON viso.JobID = #JobID
AND viso.ValidationItemID = vi.ValidationItemID
WHERE
vi.Inactive=0
AND viso.ValidationItemID IS NULL
END
GO
Got it I think
Replacing the right join with this:
LEFT JOIN
ValidationItemSignOff viso
ON viso.JobID = #JobID
AND viso.ValidationItemID = vi.ValidationItemID
If you're on 2008 or above...
MERGE INTO ValidationItemSignOff As Target
USING (SELECT DISTINCT #JobID, vi.ValidationItemID, #Login
FROM RunOffAnswer roa INNER JOIN
Method m
ON m.MethodID = roa.MethodID INNER JOIN
RunOffValidationItem vi
ON vi.ValidationItemID = m.ValidationItemID
WHERE vi.Inactive = 0) As Source (JobID, ValidationItemID, Login)
ON Target.JobID = Source.JobID
AND Target.ValidationItemID = Source.ValidationItemID
WHEN NOT MATCHED BY TARGET THEN
INSERT (JobID, ValidationItemID, CreatedBy)
VALUES (Source.JobID, Source.ValidationItemID, Source.Login);
Disclaimer: I may have not got the syntax spot on here.
I got it with this:
ALTER PROCEDURE insSignOffTemplate
#JobID varchar(50),
#Login varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO
ValidationItemSignOff
(
JobID,
ValidationItemID,
CreatedBy
)
SELECT
DISTINCT
#JobID,
vi.ValidationItemID,
#Login
FROM
RunOffAnswer roa
INNER JOIN
Method m
ON
m.MethodID = roa.MethodID
INNER JOIN
RunOffValidationItem vi
ON
vi.ValidationItemID = m.ValidationItemID
LEFT JOIN
ValidationItemSignOff viso
ON viso.JobID = #JobID AND viso.ValidationItemID = vi.ValidationItemID
WHERE
vi.Inactive=0
AND viso.ValidationItemID IS NULL
END
GO

Resources